HOW TO MERGE MANY .TXT FILES WITH A LOOP?

13 views (last 30 days)
Ivan Mich
Ivan Mich on 20 Apr 2020
Commented: Adam Danz on 10 Jun 2020
Hello,
I have a question? How could I merge many txt files in one file with a loop? For example I have File1, File2, File3.txt, ..... , . in the same directory

Answers (1)

Mehmed Saad
Mehmed Saad on 20 Apr 2020
File_all contains data of all file.
fid_p = fopen('File_all.txt','w'); % writing file id
x = 1:100;
for i =1:length(x)
filename = ['File',num2str(x(i)),'.txt'];%filename
fid_t=fopen(filename,'r');%open it and pass id to fscanf (reading file id)
data = fscanf(fid_t,'%c');%read data
fprintf(fid_p,'%c',data);%print data in File_all
fclose(fid_t);% close reading file id
end
fclose(fid_p); %close writing file id
  5 Comments
Rik
Rik on 10 Jun 2020
You can add a newline:
fid_p = fopen('File_all.txt','w'); % writing file id
x = 1:100;
for i =1:length(x)
filename = ['File',num2str(x(i)),'.txt'];%filename
fid_t=fopen(filename,'r');%open it and pass id to fscanf (reading file id)
data = fscanf(fid_t,'%c');%read data
fprintf(fid_p,'%c',data);%print data in File_all
fclose(fid_t);% close reading file id
fprintf(fid_p,'\n');%add newline
end
fclose(fid_p); %close writing file id
Adam Danz
Adam Danz on 10 Jun 2020
Ivan Mich, don't forget to accept the answers to questions that were helpful to you. You've got lots of answers but few are accepted. If the answers weren't helpful, leave feedback so future visitors can benefit from the dialog. Here's a list of your questions.

Sign in to comment.

Categories

Find more on File Operations 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!