Python:Shutil.copyfile 引发 FileNotFoundError:但文件位于指定的路径中

发布于 2025-01-11 23:12:22 字数 1160 浏览 1 评论 0原文

我正在尝试在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文