how to read file with name consist of number and string
32 次查看(过去 30 天)
显示 更早的评论
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
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 个)
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!