多文件读取

时间:2016-10-03 22:05:45

标签: matlab file-read

我在一个文件夹中有超过10,000个csv文件,文件名是0,1,2,3 ......就像那样。我想阅读它们并写入一个文件进行进一步处理。我试过这个

files= dir('C:\result\*.csv');
outs = cell(numel(files),1) 
for i = 1:numel(files)   
out{i} = csvread('%i',2,0) 
end 

但它没有用。

1 个答案:

答案 0 :(得分:0)

我不是将它们作为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);