多文件读取
Multiple file reading
我在一个文件夹中有超过 10,000 个 csv 文件,文件名是 0,1,2,3... 这样。我想阅读它们并写入一个文件以供进一步使用 processing.I 试过这个
files= dir('C:\result\*.csv');
outs = cell(numel(files),1)
for i = 1:numel(files)
out{i} = csvread('%i',2,0)
end
但是没用。
与其将它们读入 csv 文件,不如读入原始文件并再次写出。这可能会快得多。
files = dir('C:\result\*.csv');
filenames = fullfile('C:\result', {files.name});
% Sort the files based on their number
[~, ind] = sort(str2double(regexp(filenames, '[0-9]+(?=\.csv$)', 'match', 'once')));
filenames = filenames(ind);
% Open the file that you want to combine them into
outfile = 'output.csv';
outfid = fopen(outfile, 'wb');
for k = 1:numel(filenames)
% Open each file
fid = fopen(filenames{k}, 'rb');
% Read in contents and remove any trailing newlines
contents = strtrim(fread(fid, '*char'));
% Write out the content and add a newline
fprintf(outfid, '%s\n', contents);
% Close the input file
fclose(fid);
end
fclose(outfid);
我在一个文件夹中有超过 10,000 个 csv 文件,文件名是 0,1,2,3... 这样。我想阅读它们并写入一个文件以供进一步使用 processing.I 试过这个
files= dir('C:\result\*.csv');
outs = cell(numel(files),1)
for i = 1:numel(files)
out{i} = csvread('%i',2,0)
end
但是没用。
与其将它们读入 csv 文件,不如读入原始文件并再次写出。这可能会快得多。
files = dir('C:\result\*.csv');
filenames = fullfile('C:\result', {files.name});
% Sort the files based on their number
[~, ind] = sort(str2double(regexp(filenames, '[0-9]+(?=\.csv$)', 'match', 'once')));
filenames = filenames(ind);
% Open the file that you want to combine them into
outfile = 'output.csv';
outfid = fopen(outfile, 'wb');
for k = 1:numel(filenames)
% Open each file
fid = fopen(filenames{k}, 'rb');
% Read in contents and remove any trailing newlines
contents = strtrim(fread(fid, '*char'));
% Write out the content and add a newline
fprintf(outfid, '%s\n', contents);
% Close the input file
fclose(fid);
end
fclose(outfid);