Using a variable with fwrite and next line

조회 수: 83 (최근 30일)
bws1007
bws1007 2019년 9월 25일
댓글: dpb 2019년 10월 4일
So i have written a loop that reads a series of .txt files line by line and consolidates them all into a new .txt file. The problem is that it just globs them all in there and I cannot figure out how to have it go to the next line after writing one.
steve = fopen('JuneWeather.txt','at');
for i =152:181
filename= sprintf('weather_data_2019_%d.txt', i);
fid1=fopen(sprintf('%s%d',path,filename)); %.... open the file, MATLAB assigns an ID
count=-1; % line counter
while ~feof(fid1) % test for end of file (EOF)
line=fgetl(fid1); % get the next line
%disp(line); % show the line
%confile = fopen('JuneWeather.txt')
fwrite(steve, line);
fwrite(steve, '\n');
count=count+1;
% if count>100; break; end; % only for debugging
if count==0; continue; end % skip the header line
% header line in the file:
% Datetime,RecNbr,WS_mph_Avg,PAR_Den_Avg,WS_mph_S_WVT,WindDir_SD1_WVT,AirTF_Avg,Rain_in_Tot,RH,WindDir_D1_WVT
% return; %... stops script right here
end
fclose(fid1);
end
fclose(steve)
The best result I have gotten is a \n between each line, no line breaks.
Thanks!
  댓글 수: 4
bws1007
bws1007 2019년 9월 25일
편집: dpb 2019년 10월 4일
WAIT dpb! come back!
So i had to make some changes due to... well stuff.
So took each string, split it, took the parts i wanted and jamed it back together into a string..... and now next line doesnt work again...
steve = fopen('JuneWeather5.txt');
for i =152:181
filename= sprintf('weather_data_2019_%d.txt', i);
fid1=fopen(sprintf('%s%d',path,filename)); %.... open the file, MATLAB assigns an ID
count=-1; % line counter
while ~feof(fid1) % test for end of file (EOF)
line=fgets(fid1); % get the next line
count=count+1;
% if count>100; break; end; % only for debugging
if count==0; continue; end % skip the header line
la=strsplit(line,','); %.... split the line on commas, store in array la
t1(count)=la(1); % save the time tag
W(count)=str2double(la(3));
F(count)=str2double(la(7)); % convert the string to a number
R(count)=str2double(la(4));
walk = {t1(count), W(count), R(count), F(count)};
walks= string(walk);
fline = strjoin(walks,',');
fwrite(steve,fline);% if use fgets so newline is in the input line
end
fclose(fid1);
end
fclose(steve);
It writes it to the new file, but once again, no new line.
dpb
dpb 2019년 10월 4일
Well, the \n is in the original file only at the end of each record--but when you break the line apart, the delimiters are lost as well as the newline in the output--you have to put the fields back together again for the full record. Unfortunate that TMW hasn't built an easy-to-use CSV file generator routine for generic data other than csvwrite for numeric altho you could change your processing to hold the new file content in memory and then write the whole thing with writetable
As AK suggests, either mung on the string to insert the commas back into it or, build the proper format string dynamically for fwrite--
fmt=[repmat('%s,',1,numel(la)-1) '%s\n']; % comma-delimited record
fprintf(steve,fmt,fline)

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2019년 10월 4일
The stated purpose for the fwrite function, according to the top of its documentation page, is to "Write data to binary file" (emphasis added.) But you're writing to a file with the extension .txt which suggests you're trying to write text data. For that purpose, fprintf would be a more appropriate choice if you want to using low-level file I/O functions.
But depending on exactly how you want the data to be formatted, a higher-level function may be more appropriate for this application. The csvwrite or dlmwrite functions may be useful, as might the save function with the -ascii qualifier.
As an additional FYI, there's a function newline that adds a newline character to a char or string array.
S = ['Hello' newline 'World']

추가 답변 (1개)

Asvin Kumar
Asvin Kumar 2019년 10월 4일
Consider replacing the appropriate line of code with the following:
fline = strjoin(walks,',');
fline = strjoin({fline,''},'\n');
The first line of code adds commas in between the strings.
The second line of code creates a cell array consisting of fline and a temporary empty string to add the new line character (\n) between the two.
For more details have a look at the documentation for strjoin:

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by