Code for looping through a folder and sub-folders within that folder to get .csv files and move them to the main path
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
So I have a main folder on the desktop called 'Jasper_190319'.
Within this folder there are 5 sub-folders, called:
'Jasper_190319_104907', 'Jasper_190319_113628', 'Jasper_190319_125141', 'Jasper_190319_131031' and 'Jasper_190319_133135'.
These folders may or may not contain .csv files. I want help writing a code that will select the main folder, and loop through the sub-folders, find the .csv files (if present) and move them to the main path (which is where the main folder is stored).
Could anyone help me with this? Will really appreciate it!!!
EDIT: I also have another question, if I wanted to read the csv files into a table on the main path, how would I do that?
0 Kommentare
Antworten (1)
Mohammad Sami
am 4 Nov. 2019
You can use the dir function to list the folders and files in any folder.
You can use the movefile function to move the files to a new location.
It would go something like this
mainpath = uigetdir; % open gui to select main path
mainfileandfolders = dir(mainpath);
subfolders = mainfileandfolders([mainfileandfolders.isdir]); % find the subfolders
csvfiles = {};
for i = 1:length(subfolders)
subpath = fullfile(mainpath,subfolders(i).name); % path to subfolder
csvfiles{i} = dir(fullfile(subpath,'*.csv')); % list the csvfile in subfolder
end
csvfiles = vertcat(csvfiles{:}); % concatenate all csvfiles
for i = 1:length(csvfiles)
origpath = fullfile(csvfiles(i).folder,csvfiles(i).name);
[status,message,messageId] = movefile(origpath,mainpath,'restricted','f') % see doc movefile
end
9 Kommentare
Walter Roberson
am 4 Nov. 2019
I suspect that there might not be a header on the csv files; if that is the case, then the readtable() call should have 'readvariablenames', false added to the call.
Ayesha Batool
am 28 Jan. 2020
@muhammad Sami
in your code above where do you give the path to the main folder:
mainpath = uigetdir; % open gui to select main path
mainfileandfolders = dir(mainpath);
subfolders = mainfileandfolders([mainfileandfolders.isdir]); % find the subfolders
My main folder is
D:\PhD\Research\Experimental Design\Experiment 1\DATA\Analysis\Nystrom\100514\DetectionResults\
Siehe auch
Kategorien
Mehr zu Search Path finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!