Python:Shutil.copyfile 引发 FileNotFoundError:但文件位于指定的路径中
我正在尝试在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'
有谁知道我在这里做错了什么或如何解决这个问题?
非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论