how to merge multiple csv files (or xlsx files)

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.

Answers (1)

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

Sir/Madam,
I do not get any output of merged data.
Best regards,
I have edited to correct a mistake.
I still not getting any output. May I ask in which variable the final output(merged data) is saved.
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.

Sign in to comment.

Tags

Asked:

on 28 Jan 2016

Commented:

on 29 Jan 2016

Community Treasure Hunt

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

Start Hunting!