-1

I am copying a list of images from one folder to the other. The list contains some image names that is not in the source folder. I have to copy only those image names that are both in the list and the source folder and ignore the missing names.

import shutil
import os

dst = r"C:/user/data1/"

with open('test.txt') as my_file:
    for filename in my_file if os.path.exists(filename):
        file_name  = filename.strip()
        src = r'C:/user/data2/'+ file_name    
        shutil.copy(src, dst + file_name)
    
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
shiva
  • 1,177
  • 2
  • 14
  • 31
  • 1
    Does this answer your question? [Python: Error Handling](https://stackoverflow.com/questions/30043137/python-error-handling) – Chris Dec 14 '21 at 19:11

1 Answers1

2

Check if the file exists before copying it:

with open('test.txt') as my_file:
    for filename in my_file:
        src = f"C:/user/data2/{filename.strip()}"
        if os.path.exists(src):
            shutil.copy(src, dst + file_name)
not_speshal
  • 22,093
  • 2
  • 15
  • 30