Copying files based on a text file from a source folder that contains multiple sub-folders to a destination folder
1 次查看(过去 30 天)
显示 更早的评论
I have a text file containing the names of images. These images have to be copied from a source folder that contains several sub-folders to a destination folder. The source folder has the following structure:
animals (source folder)
|-cats_1
|-cats_2
|-tigers_1
|-lions_1
|-lions_2 (sub-folders)
Below is the Python equivalne code in this regard. Need assistance in performing this operation in Matlab.
import os
import shutil
src = r'X:\animals' %source with multiple sub-folders
dest = r'X:\images\cat_family' %destination folder
with open('cat_fam.txt') as file: %text file containing the image names
for path, subdirs, files in os.walk(src):
for name in file:
file_name = name.strip()
filename = os.path.join(path, file_name)
shutil.copy2(filename, dest)
0 个评论
回答(1 个)
Rik
2023-1-25
The readlines function will allow you to read a text file (storing each line as an element of a string vector).
The functions you're looking for inside the loop are fileparts (to extract the file name, note that it also separates the extension), and fullfile (to merge elements back to a full path. Lastly, copyfile can copy the file.
Your Python code does not check whether the target folder exists. The Matlab functions will not create the folder if it does not exist, so you may need the mkdir function.
2 个评论
Rik
2023-1-25
You're in luck: Matlab has excellent documentation, so you can read the documentation for each of the functions I mentioned and give them a try. Then you can come back with a specific question.
The implementation is not much more difficult than a few replacements and converting the syntax.
Given the number of questions you've asked so far, you appear to be serious about actually using Matlab, so you should invest some time to learn the tool you're using.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!