Skip to main content
 首页 » 编程设计

python之复制文件时出错

2024年10月25日6zhenyulu

我正在尝试编写一个简短的 Python 脚本,它将从具有特定扩展名的目录中复制所有文件,并将它们放在不同的文件夹中。这是脚本:

import os, shutil 
 
source = "C:\\TCR_Calgary\\projects\\" 
 
destination = "C:\\TCR_Calgary\\reference\\my_code\\city_of_calgary_scripts\\" 
 
extension = ".py" 
 
for root, dirs, files in os.walk(source): 
    for file in files: 
        if file.lower().endswith(extension): 
            shutil.copy2(file, destination) 

这是我得到的异常:

Traceback (most recent call last): 
  File "C:/TCR_Calgary/reference/my_code/city_of_calgary_scripts/python_script_copier.py", line 13, in <module> 
    shutil.copy2(file, destination) 
  File "C:\Program Files (x86)\Python26\lib\shutil.py", line 99, in copy2 
    copyfile(src, dst) 
  File "C:\Program Files (x86)\Python26\lib\shutil.py", line 47, in copyfile 
    raise Error, "`%s` and `%s` are the same file" % (src, dst) 
shutil.Error: `AnnoMover.py` and `C:\TCR_Calgary\reference\my_code\city_of_calgary_scripts\AnnoMover.py` are the same file 

我很困惑,因为 AnnoMover.py 不在目标文件夹中。在我看来,原始文件及其副本将是“相同的”,尽管它们的路径不同。这里显然有一些我不理解的地方。非常感谢任何帮助!

版本:Python 2.6 Interpeter:PyCharm Community Edition 3.4 操作系统:Windows 7

请您参考如下方法:

异常消息可能会更清楚一些,但最后一行应该是 shutil.copy2(os.path.join(source, file), destination) 以便源是完全限定的。