Hubert Wang

I am
Hubert Wang

Wechat Official Account
Find fun things here!

MATLAB txt 文件操作

<b></b>

再也不用 Google 怎样操作 txt 文件了。 :)

按行操作

index = 0;
strlist = {};
fidin=fopen('forread.txt');
while ~feof(fidin)
   txtline = fgetl(fidin);
   index = index + 1;
   strlist{index} = txtline;
end
fclose(fidin);

fidout = fopen('forwrite.txt','w');
for ii = 1 : index
    fprintf(fidout, '%s\n',strlist{ii});   
end
fclose(fidout);

按格式操作

textread 适用于一次性大批量读取格式统一的 txt 文件。一次读取后,下次再 textread 读取,还是会从文件头开始。

设 forread.txt 为:
1 2 3
4 5 6
7 8 9

[data1,data2,data3]=textread('forread.txt','%s%s%s');

如果数据有特定分隔符,如逗号:
1, 2, 3
4, 5, 6
7, 8, 9

[data1,data2,data3]=textread('forread.txt','%s%s%s','delimiter', ',');

跳过头 n 行:

[data1,data2,data3]=textread('forread.txt','%s%s%s','headerlines', n);

实用工具文,欢迎在署名加链接, http://mr-why.com条件下随意转载。

欢迎关注微信公众号 MRWHY,聊 WEB,聊 AI。

1445
TOC
Comments
Write a Comment