File not found error when copying images from one folder to another

Question:

I have a text file containing the names of images to be copied from a source folder to a destination folder. The source folder contains several sub-folders as shown below. The images may come from any of these sub-folders.

animals (source folder)
|-cats_1 
|-cats_2 
|-tigers_1 
|-lions_1 
|-lions_2 

Shown below is the Python code:

import os
import shutil
src = r'X:animals' #source with multiple sub-folders
dest = r'X:imagescat_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)

I encounter a file not found error as shown below:

  File "C:UsersAppDataLocalTemp2/ipykernel_30556/2100413787.py", line 6, in <module>
    shutil.copy2(filename, dest)

  File "C:UsersAppDataLocalContinuumanaconda3envstf2.7libshutil.py", line 266, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)

  File "C:UsersAppDataLocalContinuumanaconda3envstf2.7libshutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:

FileNotFoundError: [Errno 2] No such file or directory: 'X:\animals\lion_2345.jpg'
Asked By: shiva

||

Answers:

One approach would be to build a dictionary out of the data returned from os.walk()

The dictionary will be keyed on filename (not the full path) and its value will be the directory where the file resides.

Then you can read the cat_fam.txt file and lookup in the dictionary to see where it exists (if it exists!)

from os.path import join
from os import walk
from shutil import copy2

src = r'X:animals'
dest = r'X:animalscat_family'
db = dict()
for root, _, files in walk(src):
    for file in files:
        db[file] = root
with open('cat_fam.txt') as fam:
    for cat in map(str.strip, fam):
        fp = db.get(cat)
        if fp is not None:
            copy2(join(fp, cat), join(dest, cat))
Answered By: Pingu
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.