How can I sort files into different folders?

조회 수: 2 (최근 30일)
sal135
sal135 2017년 5월 5일
댓글: sal135 2017년 5월 5일
I have a folder with n amount of files. Each file is saved as follows:
1n1 - type 3.csv
2n2 - type 3.csv
77fn.csv
3n3 - type 4.csv
4n4 - type 3.csv
5n5 - type 4.csv
6n6 - type 4.csv
7n7.csv
And so on. The files end with "type 3" or "type 4" or with a random name. I need the script to save all the files that end in "type 3" in a folder named "X" and the files that end with "type 4" to be stored in a folder named "Y". And the files that don't end neither with "type 3" nor "type 4" to be stores in a folder name Z. Any information is helpful. Thank you!
ALLfiles='\All_Files\';
X='\X\;
Y='\Y\';
Z='\Z\'
folder= ALLfiles;
data3=fullfile(folder,'*.csv');
directory=dir(data3);
for w=1:length(directory)
name{w}=getfield(directory(w),'name');
name{w}= strfind(name{w},'type 3');
%insert if statement, if "type 3" exists in name of the file, movefile to X
elseif "type 4" exist in name of the file movefile to Y
else move file to Z
end

채택된 답변

Matthew Eicholtz
Matthew Eicholtz 2017년 5월 5일
Try this...
Get the filenames:
pathname = '\path\to\current\files';
ext = '*.csv'; % extension you care about
d = dir(fullfile(pathname,ext)); % get the relevant directory contents
filenames = {d(:).name}'; % relevant filenames
Create masks for the groups of files you are interested in using regexp:
mask1 = ~cellfun('isempty',regexp(filenames,'type 3'));
mask2 = ~cellfun('isempty',regexp(filenames,'type 4'));
mask3 = ~mask1 & ~mask2;
Copy (or move) the files from their source location to a new destination using copyfile (or movefile):
src = fullfile(pathname,filenames(mask1));
dest = fullfile('X',filenames(mask1));
cellfun(@copyfile,src,dest);
src = fullfile(pathname,filenames(mask2));
dest = fullfile('Y',filenames(mask2));
cellfun(@copyfile,src,dest);
src = fullfile(pathname,filenames(mask3));
dest = fullfile('Z',filenames(mask3));
cellfun(@copyfile,src,dest);
  댓글 수: 2
Matthew Eicholtz
Matthew Eicholtz 2017년 5월 5일
Hmm, can you tell me what pathname and filenames(mask1) look like for you? Pathname should be a string and filenames(mask1) should be a cell array of strings.
sal135
sal135 2017년 5월 5일
Thank you! this worked. Just needed to add a loop to run through all files

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by