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

时间:2018-08-06 08:29:03

标签: 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!')

1 个答案:

答案 0 :(得分:1)

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

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