gpt4 book ai didi

python 3.x Shutil.copy FileNotFoundError 错误

转载 作者:行者123 更新时间:2023-11-30 22:55:39 25 4
gpt4 key购买 nike

系统 Windows 8.1 Python 3.4
反复得到 FileNotFound Errno2 ,尝试复制目录中的所有文件。

import os
import shutil
source = os.listdir("C:\\Users\\Chess\\events\\")
for file in source :
shutil.copy(file, "E:\\events\\")

产量

FileNotFoundError : [Errno2] No such file or directory 'aerofl03.pgn'.

尽管'aerofl03.pgn'位于源列表['aerofl03.pgn', ...]中的第一位。如果添加一行,结果相同:

for file in source :
if file.endswith('.pgn') :
shutil.copy(file, "E:\\events\\")

如果编码则结果相同

for file in "C:\\Users\\Chess\\events\\" :

我的shutil.copy(sourcefile,destinationfile)可以很好地复制单个文件。

最佳答案

os.listdir()仅列出不带路径的文件名。如果没有完整路径,shutil.copy()将文件视为相对于当前工作目录,并且不存在 aerofl03.pgn文件位于当前工作目录中。

再次添加路径以获取完整路径名:

path = "C:\\Users\\Chess\\events\\"
source = os.listdir(path)

for filename in source:
fullpath = os.path.join(path, filename)
shutil.copy(fullpath, "E:\\events\\")

现在shutil.copy()被告知复制C:\Users\Chess\events\aerofl03.pgn ,而不是 <CWD>\aerofl03.pgn .

关于python 3.x Shutil.copy FileNotFoundError 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37333467/

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