Python: Shutil.copyfile raises FileNotFoundError: but the file is in the path that is specified

697 Views Asked by At

I'm trying to copy some files in Python of which the names contain a certain substring from a list, for this I wrote the following code:

import shutil
import os
import numpy as np

path = os.getcwd()
validate_names = np.loadtxt(fname='validation.txt', dtype=str)
label_dir = f'{path}\labels\\'
image_dir = f'{path}\images\\'
label_val_dir = f'{path}\labels\valid\\'
image_val_dir = f'{path}\images\valid\\'

for filename in os.listdir(label_dir):
    for name in validate_names:
        if name in filename:
            print(label_dir + filename)
            shutil.copyfile(label_dir + filename, label_val_dir + filename)
            shutil.copyfile(image_dir + filename[:-4]+'.jpg', image_val_dir + filename[:-4]+'.jpg')

When I print the path from/to which I copy the files it seems correct:

H:\My Drive\TrainingData\labels\2014-12-19_B09G.txt

however the shutil module raises and error; the path that is tried to access seems to have changed, adding \x0balid to the string:

  File "C:\Users\d1a9a\anaconda3\envs\yolo\lib\shutil.py", line 264, in copyfile
    with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:

FileNotFoundError: [Errno 2] No such file or directory: 'H:\\My Drive\\TrainingData\\labels\x0balid\\2014-12-19_B09G.txt'

Does anyone know what I am doing wrong here or how this can be solved?

Many thanks!

0

There are 0 best solutions below