How to move/copy files from folder and subfolders to a new folder?

26 ビュー (過去 30 日間)
Mario
Mario 2020 年 2 月 25 日
コメント済み: Mario 2020 年 2 月 28 日
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
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.
Mario
Mario 2020 年 2 月 28 日
Thank you dbp for your help on this, very appreciated.

サインインしてコメントする。

採用された回答

Jyotsna Talluri
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
Refer to the link dir for more details
  1 件のコメント
Mario
Mario 2020 年 2 月 28 日
Thank you Jyotsna for your help on this, very appreciated.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by