因此,我编写了一个循环,逐行读取一系列.txt文件,并将它们全部合并为一个新的.txt文件。问题在于,它只是将它们全部聚集到了那里,我无法弄清楚在写完一行后如何将其转到下一行。
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
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)
我得到的最好结果是每行之间\ n,没有换行符。谢谢!
有几处错误或至少使您的代码令人困惑:
首先,您以'text'
模式打开输出文件(在文件打开语句t
中由steve=fopen('JuneWeather.txt','at');
表示)。这在您处理文本文件时很好,但是随后您继续使用fwrite
,这是专门用于写入binary数据的低级函数。
[我将在下面为您提供fprintf
的解决方案,因为我真的建议对工作使用适当的功能,特别是在不确定自己在做什么的时候。
而且,您还没有想到fprintf
的定义是:从文件中读取行,删除换行符。因此,当然,您必须在每行的末尾放置一个换行符,因为每次阅读一行时,原始的换行符都会被转储。
关于要选择的换行符,可以使用类似以下的自动方法:
fgetl
但是在您的情况下,这甚至没有必要。由于您以文本模式打开了输出文件,因此文档告诉您:
要以文本模式打开文件,请在权限后面加上字母“ t”参数,例如“ rt”或“ wt +”。
在Windows®系统上,以文本模式:
fgetl
最后一行是您的线索,MATLAB将自动管理回车符(if ispc
strNewline = '\r\n' ;
else
strNewline = '\n' ;
end
字符),因此您无需理会它。仅在需要时才使用- Read operations that encounter a carriage return followed by a newline character ('\r\n') remove the carriage return from the input.
- Write operations insert a carriage return before any newline character in the output.
。
([请注意,在PC计算机上,如果您尚未以文本模式打开文件,则需要插入回车符,如果需要的话,请返回)。
出于示例的目的,我创建了2个文本文件\r
和\n
,它们仅包含一个标题和几行逗号分隔的值。可行且最接近您的实现的代码如下(我删除了有关test_1.txt
和注释的调试行,请随时在需要的地方重新插入):
test_2.txt
或者:
由于您正在使用文本文件,并且似乎只是合并,而实际上没有对读取的每一行进行任何选择/编辑/处理,因此您可以通过完整读取每个文件并将其写入来简化它一口气进入输出文件。您可以使用功能count
。
类似:
fileOut = 'testout.txt' ;
steve = fopen(fileOut,'at');
for i =1:2
fid1=fopen(sprintf('test_%d.txt', i));
while ~feof(fid1)
% This reads the line, but REMOVE the newline character at the end
line=fgetl(fid1);
% so we write the line and ADD the newline character at the end
fprintf(steve, [line '\n']);
end
fclose(fid1);
end
fclose(steve) ;
将产生与上面完全相同的输出,并且对于长文件和/或大量文件将明显更快。只需注意最后一个代码片段,该文件便像以前一样在文本模式下打开了[[NOT。否则,即使已经存在fileread
,matlab也会自动在每个fileread
之前插入%% merge text data using "fileread"
steve = fopen('testout.txt','a');
for i =1:2
StringFileContent = fileread( sprintf('test_%d.txt', i) ) ;
fprintf(steve, StringFileContent );
end
fclose(steve) ;
(实际上是复制每个\r
)。这是因为函数\n
不会与换行符混淆,它只是将所有内容读取为字符串。
如果您有matlab> 2016b,则可以只使用换行符:
\r
如果不这样做,则需要知道您所使用的操作系统:Windows:
\r
Unix:
fileread
另外,您可以看一下fprintf函数。这解释了\ n等转义序列。也请检查以下行:
fwrite(steve,newline);
我怀疑应该读为:
fwrite(steve,sprintf('\r\n'));
但是,我建议您使用该功能
fwrite(steve,sprintf('\n'));
用于处理诸如\ /的Unix / Windows系统。编辑:万一您想使用fprintf函数而不是fwrite:删除fwrite行并替换为。
fid1=fopen(sprintf('%s%d',path,filename));
(%s很重要,否则fprintf可能会将任何\字符解释为转义序列。)