HOW TO MERGE MANY .TXT FILES WITH A LOOP?

6 visualizzazioni (ultimi 30 giorni)
Ivan Mich
Ivan Mich il 20 Apr 2020
Commentato: Adam Danz il 10 Giu 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

Risposte (1)

Mehmed Saad
Mehmed Saad il 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 Commenti
Rik
Rik il 10 Giu 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 il 10 Giu 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.

Accedi per commentare.

Categorie

Scopri di più su File Operations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by