系统 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/