问题
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\\")
yields
FileNotFoundError : [Errno2] No such file or directory '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\\")
Same result if coded
for file in "C:\\Users\\Chess\\events\\" :
My shutil.copy(sourcefile,destinationfile) works fine copying individual files.
回答1:
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\\")
So now shutil.copy()
is told to copy C:\Users\Chess\events\aerofl03.pgn
, instead of <CWD>\aerofl03.pgn
.
来源:https://stackoverflow.com/questions/37333467/python-3-x-shutil-copy-filenotfounderror