python - 将文件复制到目录时出现 FileNotFoundError

标签 python shutil

我有一个文本文件“Flickr_8k.testImages.txt”,其中包含由换行符分隔的 1000 个文件的文件名。这些文件位于目录“Flickr8k_Dataset”内,其中包含 8000 多个文件。我想要做的就是将文本文件中列出的文件复制到单独的目录“dstn”中,该目录位于该脚本所在的同一路径中。 执行此脚本时显示以下错误:

Traceback (most recent call last):
File "/Users/sbs/Documents/new_script/copy_images.py", line 13, in <module>
copy(filename, dstn)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 241, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: '3385593926_d3e9c21170.jpg'

这是我的脚本。

import os
from shutil import copy2
scriptpath = os.path.dirname(__file__)
f1 = open("Flickr_8k.testImages.txt", 'r') #this file contains filenames
directory = os.path.join(scriptpath, 'Flickr8k_Dataset') #'Flickr8k_Dataset' this directory contains files
dstn = os.path.join(scriptpath, 'dstn')
count = 0
for line in f1.read().split("\n"):
    for filename in os.listdir(directory):
        if line == filename:
            copy2(filename, dstn)
            print(filename, ' copied.')
            count += 1

print(count, ' files found and copied successfully!')

最佳答案

从错误消息来看,您没有正确的文件路径。

for filename in os.listdir(directory):
    filename = os.path.join(directory, filename)
    ...

关于python - 将文件复制到目录时出现 FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51703465/

相关文章:

python - ZODB Bloat 一定是坏事吗?

Python win32 服务

python - 调用函数报错 'not subscriptable'

python - shutil.disk_usage() 中似乎存在差异

python - 将文件夹目录中的所有 .csv 文件复制到 python 中的一个文件夹中

javascript - 您可以在 Javascript 或 Python 中使用必需的关键字参数吗?

python - 使用点 (.) 访问字典键

python - 将任意长度的位置列表 [4, 1, 2] 转换为嵌套列表的索引

Python - 根据内容分隔文件

python - 禁用 Shutil.copy 中的 SameFileError 异常