python 3.x shutil.copy FileNotFoundError [英] python 3.x shutil.copy FileNotFoundError
问题描述
系统 Windows 8.1 Python 3.4
反复获取 FileNotFound Errno2 ,试图复制目录中的所有文件.
system Windows 8.1 Python 3.4
Repeatedly get FileNotFound Errno2 , attempting to copy all files in a directory.
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', ...]
.如果添加一行,结果相同:
Although 'aerofl03.pgn'
is first in the source list ['aerofl03.pgn', ...]
.
Same result if a line is added:
for file in source :
if file.endswith('.pgn') :
shutil.copy(file, "E:\\events\\")
编码结果相同
for file in "C:\\Users\\Chess\\events\\" :
我的 shutil.copy(sourcefile,destinationfile) 可以很好地复制单个文件.
My shutil.copy(sourcefile,destinationfile) works fine copying individual files.
推荐答案
os.listdir()
只列出没有路径的文件名.如果没有完整路径,shutil.copy()
会将文件视为相对于您当前工作目录的文件,并且您当前工作目录中没有 aerofl03.pgn
文件.
os.listdir()
lists only the filename without a path. Without a full path, shutil.copy()
treats the file as relative to your current working directory, and there is no aerofl03.pgn
file in your current working directory.
再次添加路径以获取完整路径名:
Prepend the path again to get the full pathname:
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
,而不是
.
So now shutil.copy()
is told to copy C:\Users\Chess\events\aerofl03.pgn
, instead of <CWD>\aerofl03.pgn
.
这篇关于python 3.x shutil.copy FileNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!