Copying files based on a text file from a source folder that contains multiple sub-folders to a destination folder

2 views (last 30 days)
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)

Answers (1)

Rik
Rik on 25 Jan 2023
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 Comments
Rik
Rik on 25 Jan 2023
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.

Sign in to comment.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!