python 3.x shutil.copy FileNotFoundError

自闭症网瘾萝莉.ら 提交于 2021-02-19 08:47:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!