Read all text files in folder (nonsequential)
9 次查看(过去 30 天)
显示 更早的评论
I need matlab to read all text files within a folder. The number typically are sequential; however, the limitation of the existing MATLAB script is that it doesn’t allow for non-consecutive numbered tests, beginning only at xxxx001.dat to be processed. I would like all .dat files contained within a specific folder to be processed at the same time.
RT_number=1917; t1start=tic; warning off MATLAB:xlswrite:AddSheet;
for i=1:999 tic; if i>=1 && i<=9
zero='00';
end
if i>=10 && i<=99
zero='0';
end
if i>=100 && i<=999
zero='';
end
filename=[int2str(RT_number) zero int2str(i) '.dat'];
end
fid=fopen(filename);
0 个评论
采纳的回答
Kelly Kearney
2014-5-23
F = dir('*.dat');
for ii = 1:length(F)
fid = fopen(F(ii).name);
end
By the way, if they are sequential, a cleaner way to get the file names:
RT_number=1917;
for ii = 1:999
filename = sprintf('%d%02d.dat', RT_number, ii);
fid = fopen(filename);
end
2 个评论
Kelly Kearney
2014-5-23
I suggest reading the help for dir. In this case, F(ii).name holds the same string as filename in your original example, i.e. the name of the file. You could add an extra line:
filename = F(ii).name;
but it's unnecessary (I'd only do that if you have a lot of code that already refers to the filename variable.)
更多回答(1 个)
Mahdi
2014-5-23
Based on what you said, if you have all the files in the same folder, you can open the folder in MATLAB and use dir to list all the folder contents (With other options if you want, or even tell dir which folder to list the contents for). Similarly, you can use ls.
You can then use a loop to open up these files, for example (assuming you're in the folder already)
filelist=ls;
[m, n] size(filelist);
for i=1:m
fid=fopen(filename(i,1:end))
end
You can do the same thing dir, but you would need to use filelist(i).name
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!