read all text files in a directory

Hi,
I' like the code to read all the files in a directory, applying it manually it would have been:
load textfile1.txt
load textfile2.txt
load textfile3.txt
...
Thank you

Answers (2)

Sajid Afaque
Sajid Afaque on 12 Jan 2023
Edited: Sajid Afaque on 16 Jan 2023
try to use the below general approach
data_files=dir_listing(datapath,'*.txt') %reads all text files at the location specified by datapath
for e=1:numel(data_files)
%read the data from individual files
fid=fopen(fullfile(datapath,data_files{e}));
data_1=textscan(fid,'%s','delimiter','\n');
fclose(fid);
%then deal however you want to treat the data
end

8 Comments

@Shulamit Nussboim was it helpful ?, if yes please do accept answer as it would help other people in the community
It read the directory files but something is wrong and not opening the files.
you need *.txt not .txt$
OK, thank you both so much!
Sajid Afaque
Sajid Afaque on 16 Jan 2023
Edited: Sajid Afaque on 16 Jan 2023
yeah , i overlooked it , corrected now. @Shulamit Nussboim please do accept the answer by clicking on "accept answer", if it has solved your problem
What is 'dir_listing' in your code?
function files = dir_listing(folder, spec)
dinfo = dir(fullfile(folder, spec)) ;
files = {dinfo.name};
end
Thanks walter. dir_listing would be a seperate function to list the names of all the files of particular format(here text files) from a specified directory

Sign in to comment.

Categories

Products

Release

R2022a

Asked:

on 12 Jan 2023

Commented:

on 17 Jan 2023

Community Treasure Hunt

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

Start Hunting!