Code for looping through a folder and sub-folders within that folder to get .csv files and move them to the main path
5 ビュー (過去 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?
0 件のコメント
回答 (1 件)
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
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
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 Center および File Exchange で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!