how to read file with name consist of number and string

조회 수: 46 (최근 30일)
Samaneh Arzpeima
Samaneh Arzpeima 2018년 9월 20일
편집: Stephen23 2021년 4월 18일
Hello I have a folder(name is Site) with lots of .dat file in it. (site1g.dat site2g.dat site3g.dat site4s.dat site5s.dat site6s.dat site7m.dat ...). I want to read all the files and use their data to do some simulations.
pathToFolder = './Site';
files = dir( fullfile(pathToFolder,'*.dat') );
data = cell(numel(files),1);
index = 'g s m d o f a h i j'
for i=1:numel(files)
fid = fopen([pathToFolder '/site' num2str(i) 'index' '.dat'], 'rt');
H = textscan(fid, '%s', 21, 'Delimiter','\n');
C = textscan(fid, repmat('%f ',1,8), 'Delimiter',' ', ...
'MultipleDelimsAsOne',true, 'CollectOutput',true);
fclose(fid);
H = H{1}; C = C{1};
but it wont read the files.can anyone help me with this code. I somehow undesratnd the alphabets inside the filenames doing wrong,but.. I really appreciate any comment. Thank you
#BTW each .dat file has 21line of header and 80000 row of data come after it.

채택된 답변

Stephen23
Stephen23 2018년 9월 21일
편집: Stephen23 2021년 4월 18일
You are mixing up two different paradigms for handling multiple files: first you use dir to get all of the names of any .dat files in some folder... and then you totally ignore those filenames and instead try to generate names using num2str and string concatenation. There is no point in trying to mix everything together like that: just use dir to get the filenames, and then use them! Try something like this instead:
opt = {'Delimiter',' ', 'MultipleDelimsAsOne',true, 'CollectOutput',true};
D = './Site';
S = dir(fullfile(D,'*.dat'));
S = natsortfiles(S); % alphanumeric sort by filename
for k = 1:numel(S)
[fid,msg] = fopen(fullfile(D,S(k).name),'rt');
assert(fid>=3,msg)
H = textscan(fid, '%s', 21, 'Delimiter','\n');
C = textscan(fid, repmat('%f ',1,8), opt{:});
fclose(fid);
...
end
You can download natsortfiles here (it is optional):
  댓글 수: 1
Samaneh Arzpeima
Samaneh Arzpeima 2018년 9월 21일
WOW the run time was fast! thank you verymuch. asking here did well.

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

추가 답변 (1개)

Krithika A
Krithika A 2018년 9월 20일
Go to the Home tab>import data. there you can select a single data set you want to use in matlab. Once there, you can create a function that you can use to import the same type of data sets. You can of course use this function in a for loop to import all the data sets at once. Look at the code to see what it's doing so you can use it in future.
  댓글 수: 1
Samaneh Arzpeima
Samaneh Arzpeima 2018년 9월 21일
Thank you Yes I know about the import data tool. I made the loop,it worked when all the files name were in a descending order.but when the files name got complex the loop was not work.

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

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by