我正在尝试在 Python 中复制一些文件,这些文件的名称包含列表中的某个子字符串,为此我编写了以下代码:
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')
当我打印从/复制文件的路径时,它似乎是正确的:
H:\My Drive\TrainingData\labels\2014-12-19_B09G.txt
但是shutil模块引发和错误;尝试访问的路径似乎已更改,将 \x0balid 添加到字符串中:
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'
有谁知道我在这里做错了什么或如何解决?
非常感谢!