python 3.x Shutil.copy FileNotFoundError 错误

标签 python python-3.4 shutil

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

相关文章:

python - 我正在使用 python 制作计算器,它显示计算带括号的表达式时出错

python - 打印到屏幕时获取用户输入

python-3.x - Pandas 数据框所有列的平均值?

python - `shutil.rmtree` 不适用于 `tempfile.TemporaryDirectory()`

用os模块覆盖python文件

python - generator.throw() 有什么用?

python - Celery 由于预取而执行多任务

python - 尝试为 Python 3 安装 scikit-learn 时出现 "Cannot fetch index base URL"错误消息

python - 运行 pip install --allow external 时 Mysql python 连接器不可用

python - 如何改进在 Python 中移动所有不包含特定日期的文件?