gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:10:26 28 4
gpt4 key购买 nike

我有一个文本文件“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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com