Using a variable with fwrite and next line
Mostra commenti meno recenti
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 Commenti
dpb
il 25 Set 2019
Instead of fgetl use fgets and you'll get the newline character in the returned line and it'll be written as well.
Need format spec for the output file as well...
fwrite(steve,'%s',line) % if use fgets so newline is in the input line
or
fwrite(steve,'%s\n',line) % if use fgetl so no newline kept on read
bws1007
il 25 Set 2019
dpb
il 4 Ott 2019
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)
Risposta accettata
Più risposte (1)
Asvin Kumar
il 4 Ott 2019
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:
Categorie
Scopri di più su Characters and Strings in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!