Search code examples
pythonshutillistdir

shutil can not find existing file using os.listdir


I have a big pool of images in which I folder them by using jpg filenames. Right now, I'm recieving: FileNotFoundError: [Errno 2] No such file or directory 'Z4554545.jpg'

However Z4554545.jpg exist within /images folder. What am I doing wrong here? Note:I'm using Jupyter notebook.

path=r'C:/Users/images'
dst_dir=r'C:/Users/images/new'


for file in os.listdir(path):
    if file in id_final2:
        shutil.copy(file, dst_dir)
    elif file in id_final:
        shutil.copy(file, dst_dir)

Solution

  • os.listdir does not include the path in the file, so if you are not running the script in C:/Users/images, shutil.copy will essentially try to copy the file from os.curdir

    To fix your code:

    path=r'C:/Users/images'
    dst_dir=r'C:/Users/images/new'
    
    
    for file in os.listdir(path):
        if file in id_final2:
            shutil.copy(os.path.join(path, file), dst_dir)
        elif file in id_final:
            shutil.copy(os.path.join(path, file), dst_dir)