Code for looping through a folder and sub-folders within that folder to get .csv files and move them to the main path

11 次查看(过去 30 天)
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?

回答(1 个)

Mohammad Sami
Mohammad Sami 2019-11-4
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 个评论
Walter Roberson
Walter Roberson 2019-11-4
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
Ayesha Batool 2020-1-28
@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\

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by