How to move/copy files from folder and subfolders to a new folder?
19 次查看(过去 30 天)
显示 更早的评论
Hello,
I am trying to move/copy files from a main folder with multiple subfolders to a new folder.
The code below runs but I receive this error when I use this is in the loop...
for k = 1:numel(FilesName):
...
Error using movefile
No matching files were found.
Here is my attempt...
clear all, close all,
% Folders/subfolders where files are located
% I want to move only the .png files located under D:\2015\
myDir = dir('D:\2015\**\**\*.png');
% New destination folder
destFolder = 'D:\NewFolder';
%Cell array with file names
FilesName = {myDir.name};
for k = 1:numel(FilesName)
sourceFile = fullfile(myDir(k).folder, myDir(k).name);
movefile(sourceFile, destFolder);
end
whos
Name Size Bytes Class Attributes
FilesName 1x5022 1051326 cell
destFolder 1x12 24 char
k 1x1 8 double
myDir 5022x1 4280856 struct
However, when I use... for k = 1:3:numel(FilesName) the code does what I want (move all .png files under folder D:\2015\...
My question is why myDir above is repeating the same file name 3 times? I believe that is because when k=2 cannot find the file as it was already moved. Then, I am obligated to skip every 3 files. Maybe I am using the wildcards in the wrong context here?
Your comments are welcome.
4 个评论
dpb
2020-2-26
Well, that would indicate that's how many files there are in toto, then -- at least with that wildcard pattern.
Have you exhaustively verified you have the subdirectories wanted and only the subdirectories wanted?
I forget who wrote it but at least one of the other regulars here has written examples of recursive subdirectory traversing...do a search by subject for the phrase. There may also be (and almost certainly is) submissions at the File Exchange.
采纳的回答
Jyotsna Talluri
2020-2-28
编辑:Jyotsna Talluri
2020-2-28
To list all files with a particular extension in all folders and subfolders,you can use dir ( <path> /**/* <extension>) .In your code
myDir = dir('D:\2015\**\**\*.png')
considers each subfolder recursively in the folder D:\2015 and lists files with .png extension in all the folders and subfolders , due to which each file is listed many times. Just use
myDir = dir('D:\2015\**\*.png')
to list all files with .png extension in all folders and subfolders in this path D:\2015
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!