Merging the Data in the Text Files for the Number of "N" Text Files

Hello,
In my directory I have N numbers of text files and I want to read all of them with the datas that they contain. After that, I want to merge these N text files to just one text file. What I did was finding the text files in the directory and find their names, I could not read them and merge them. Thanks for your help.
clc
clear
close all
directory = 'C:\me\me\Desktop\directory';
fileList = dir(fullfile(directory, '*.txt'));
names_temp = struct2cell(fileList);
text_name = names_temp(1,:);

 Accepted Answer

Hey,
there's a lot of ways to read text files. For your purposes, I think fileread and fscanf functions might do well.
Then, you can merge them, which depends on the data type that will be output of your reading.

4 Comments

Yes I can read them individually but i want to read them for the number of text files that the directory contains. Like for loop.
A = fileread(text_name(1, :))
B = fileread(text_name(2, :))
C = fileread(text_name(3, :))
[A B C]
it will not solve my problem since I will not know how much text files inside of the directory have.
Use length to get number of files.
I'll share with you my own code that I use to get folder content.
files = dir(path); % all files from the folder
format = '.txt'; % specify format of the files (.txt, .xlsx etc.)
for o = 1:length(files)
idx(o) = contains(files(o).name,format); % logical vector representing .txt files
end
txtfiles = struct2cell(files(idx))'; % txt files = all txt
if size(txtfiles) == [0 1]
error 'No .txt files found. Try choosing the correct folder.'
end
Then, you will have cell with names of your files. You can use it's length again to go through it in a for loop.
[X Y] = size(txtfiles); % X = length
path = strcat(path,'\'); % missing backslash in directory
for q = 1:X
location = strcat(path,txtfiles(q,1)); % will create path to load the data
data{1,q} = readmatrix(location{1}); % will save all your data into cell
end
Hope I helped.
This is my old piece of code, there might be a simpler way but it should work.
Basically; you create a for loop that goes for the size of number of your files and you load them into a cell. Or you can process them (for example: merge them) in the for loop instantly instead of saving them.
When I run this code, it gives me some cell arrays but inside of the cell arrays I see NaN values. Have you got any opinion about it sir? Thanks.
oh, yes. readmatrix was function that i used to load my data. you should use your method to load the text data. maybe fileread or fscanf as i mentioned above.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2019b

Community Treasure Hunt

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

Start Hunting!