How to copy only the images listed in a text file from one folder to another while ignoring the missing images?

Question:

I have written the code to copy only the images listed in a CSV file under the column ‘ID’ from source folder to destination folder. However, there are several image names listed in the CSV file that are not present in the source folder. I have to ignore those missing images and copy only those available in the source folder to the destination folder. The current code throws an error when it encounters a image name in the CSV file that is not present in the source folder.

import csv
import os
import shutil

source = r'C:source_foldersource_images'
destination = r'C:dest_folderdest_images'

with open('data.csv') as csvfile:
       reader = csv.DictReader(csvfile)
       for column in reader:
           shutil.copyfile(os.path.join(source, column['ID']), os.path.join(destination, column['ID']))
Asked By: shiva

||

Answers:

Converting from comment to answer:

import csv
import os
import shutil

source = r'C:source_foldersource_images'
destination = r'C:dest_folderdest_images'

with open('data.csv') as csvfile:
       reader = csv.DictReader(csvfile)
       for column in reader:
           if os.path.exists(os.path.join(source, column['ID'])) and os.stat(os.path.join(source, column['ID'])).st_size != 0:
               shutil.copyfile(os.path.join(source, column['ID']), os.path.join(destination, column['ID']))
Answered By: user56700

What directory should the csv reside in? I’ve tried both but I’m given the following error:

Traceback (most recent call last):
File "", line 1, in
FileNotFoundError: [Errno 2] No such file or directory: ‘data.csv’

Answered By: Kate