登录论坛

查看完整版本 : 如何编写与在MATLAB中读取的格式相同的文本文件?


poster
2019-12-10, 16:49
过去我曾问过一个相关的问题 (https://stackoverflow.com/questions/1641519/reading-date-and-time-from-csv-file-in-matlab) ,在这里专家的帮助下,我知道如何读取文件。现在我有一个新问题。我首先像这样从文件中读取数据:

fid = fopen('D:\file.txt', 'rt'); a = textscan(fid, '%s %f %f %f %f %f %f', ... 'Delimiter',',', 'CollectOutput',1, 'HeaderLines',1); fclose(fid); 然后,我处理文件并更改列的一些值。现在,我想以与我的file.txt完全相同的格式编写一个新文件newfile.txt ,并带有新值。我怎么做?

如果我执行以下操作:

M = [datenum(a{1}) a{2}]; dlmwrite('newfile1.txt', M); 它给我一个新文件,没有我的第一行标题,也没有我想要的格式的第1列和第2列。

我的文件格式如下:

date time, M01, M02, M03, M04, M05, M06 8/15/2009, 0:00:00, 5.8, 7.8, 7.8, 7.3, 0, 7.9 8/15/2009, 0:10:00, 7.1, 8.1, 8.1, 7.7, 0, 8.1 8/15/2009, 0:20:00, 6.8, 7.4, 7.6, 7.1, 0, 7.3 8/15/2009, 0:30:00, 5.6, 6.8, 7.1, 6.6, 0, 6.8 8/15/2009, 0:40:00, 3.9, 6.2, 6.4, 6.2, 0, 6.4 8/15/2009, 0:50:00, 4.6, 5.5, 6.1, 5.8, 0, 5.6 8/15/2009, 1:40:00, 7, 7, 7.2, 6.9, 0, 6.3 我能够以格式创建新的file.txt

我的文件格式如下:

5.8, 7.8, 7.8, 7.3, 0, 7.9 7.1, 8.1, 8.1, 7.7, 0, 8.1 6.8, 7.4, 7.6, 7.1, 0, 7.3 5.6, 6.8, 7.1, 6.6, 0, 6.8 3.9, 6.2, 6.4, 6.2, 0, 6.4 4.6, 5.5, 6.1, 5.8, 0, 5.6 7, 7, 7.2, 6.9, 0, 6.3 有人可以帮我2将标题和前两列复制到此新文件中吗?


回答:
注意:我已经更新了答案,以使用问题中指定的最新文件格式(即日期和时间值之间的逗号)。我还编写了以下代码来处理非常大的文件,在这些文件中,列数是已知的,但行数是可变的。

首先,您必须使用以下更新的代码读取文件(使用代码FGETS (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fgets.html)保存第一行):

fid = fopen('D:\file.txt','rt'); %# Open the file topLine = fgets(fid); %# Read the top line and store it in a string data = textscan(fid,'%f','Delimiter',',/:'); %# Read the data fclose(fid); %# Close the file 接下来,您必须使用已知的数据列数来重塑data ( 不计算日期和时间列):

N = 74; %# Number of columns of data after the date and time data = reshape(data{1},N+6,[])'; 现在, data是一个矩阵,其中前六列包含日期和时间信息(月,日,年,小时,分钟和秒),而所有其他数据在其余N列中。如果您需要对日期和时间值做任何事情,可以查看以下函数以弄清楚如何将它们转换为不同的格式: DATENUM (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/datenum.html) , DATESTR (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/datestr.html)和DATEVEC (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/datevec.html) 。

修改data的值之后,可以使用for循环和FPRINTF (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html)函数重新保存它:

fid = fopen('newfile1.txt','wt'); %# Open the file fprintf(fid,'%s',topLine); %# Print the top line for i = 1:size(data,1) %# Loop over the rows of data fprintf(fid,'%d/%d/%d, %d:%d:%d',data(i,1:6)); %# Print the date fprintf(fid,', %.1f',data(i,7:end)); %# Print the data fprintf(fid,'\n'); %# Print a newline end fclose(fid); %# Close the file 我使用86400 x 80矩阵运行上述代码来data ,将数据写入文件大约需要30秒。



更多&回答... (https://stackoverflow.com/questions/1905061)