Import text files from multiple folders

5 visualizzazioni (ultimi 30 giorni)
Madison Lowe
Madison Lowe il 22 Mar 2018
Commentato: Nima Sho il 21 Gen 2022
I am trying to import data from multiple text files spread out between multiple folders. In this example of a previous question, what could I do to grab data from every file in each folder, rather than just one particular file?
% Path of the main folder : Rotation
yourpath = 'H:\Inspection ProjectData\rotation1';
% Get all the subfolders
ContentInFold = dir(yourpath);
SubFold = ContentInFold([ContentInFold.isdir]); % keep only the directories
% Loop on each folder
MyData = [];
for i = 3:length(SubFold) % start at 3 to skip . and ..
filetoread = fullfile(yourpath,SubFold(i).name,'fx.txt'); % <- this is the "fx.txt" file of the ith subfolders
% then type your code to read the text files and store in one variable
fileID = fopen(filetoread);
MyData{end+1} = textscan(fileID,'%s\n'); % the format depends of your files
fclose(fileID);
end
  1 Commento
Jan
Jan il 22 Mar 2018
How are the files recognize, which you want to process? Do all files have the same name?

Accedi per commentare.

Risposte (1)

Jan
Jan il 22 Mar 2018
If all files are called "fx.txt" and you are using a Matlab version >= R2016b:
FileList = fullfile(yourpath, '**', 'fx.txt');
for iFile = 1:numel(FileList)
filetoread = fullfile(FileList(iFile).folder, FileList(iFile).name);
...
end
Note: It is not documented, that '.' and '..' are the first two folders replied by dir. This might change with the operating system and file system. Prefer a ismember(Name, {'.', '..'}.
  1 Commento
Nima Sho
Nima Sho il 21 Gen 2022
Hello Jan
Regarding the question discussed above, I have a main Folder, named 'Results', which contains 44 folders, named 1 to 44. Each of these 44, has 20 subFolders inside itself, named by some various numbers. In each of these 20, there are some txt files and I will use a specific one of them named 'drifts'.
By using above-mentioned txt files, I'll plot 44 curves, each one is made up of 20 points.
How can I address these txt files exist in multiple folders and then subfolders.
Thanks for your time and attention

Accedi per commentare.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by