Using a variable with fwrite and next line

85 visualizaciones (últimos 30 días)
bws1007
bws1007 el 25 de Sept. de 2019
Comentada: dpb el 4 de Oct. de 2019
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 comentarios
bws1007
bws1007 el 25 de Sept. de 2019
Editada: dpb el 4 de Oct. de 2019
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 el 4 de Oct. de 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)

Iniciar sesión para comentar.

Respuesta aceptada

Steven Lord
Steven Lord el 4 de Oct. de 2019
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']

Más respuestas (1)

Asvin Kumar
Asvin Kumar el 4 de Oct. de 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:

Categorías

Más información sobre Low-Level File I/O en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by