Read all text files in folder (nonsequential)

조회 수: 4 (최근 30일)
Russell
Russell 2014년 5월 23일
댓글: Russell 2014년 5월 23일
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);

채택된 답변

Kelly Kearney
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
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.)
Russell
Russell 2014년 5월 23일
Can you please explain what you did? I have a very basic understanding of Matlab

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mahdi
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
  댓글 수: 1
Russell
Russell 2014년 5월 23일
I need matlab to convert the data into an excel file. That is why I want it to open the files in the folder. It will be creating an excel sheet for each file.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by