how to merge multiple csv files (or xlsx files)
3 views (last 30 days)
Show older comments
Hi,
I have here, for example two csv files need to merge(merge into one). Can anyone kindly help how to merge them. Many thanks in advance.
0 Comments
Answers (1)
Walter Roberson
on 28 Jan 2016
Edited: Walter Roberson
on 29 Jan 2016
fout = fopen('mergedData.csv', 'wt');
in_filenames = {'previouData.csv', 'currentData.csv'};
for K = 1 : length(in_filenames)
thisfile = in_filenames{K};
fin = fopen(thisfile, 'rt');
while true
thisline = fgetl(fin);
if ~ischar(thisline); break; end %end of file
if ~isempty(thisline); %assume empty lines are trailing empty lines
fprintf(fout, '%s\n', thisline);
end
end
fclose(fin);
end
fclose(fout);
Under some circumstances you can use much shorter code: you would need to be sure that the csv files were consistent about whether they used newline only or else carriage return + newline; and you would need to know that each file ended with a line terminator. The code I have given here is as long as it is because I do not assume that the line terminators are consistent and I do not assume that there is a line terminator at end of file.
4 Comments
Walter Roberson
on 29 Jan 2016
It is not saved in a variable, it is saved in the file mergedData.csv as you asked to merge the files, not to read the files into memory.
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!