我正在尝试编写一个简短的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不在目标文件夹中。在我看来,原始文件及其副本将是相同的&#34;虽然他们的路径不会。很明显,我在这里并不理解。非常感谢任何帮助!
版本:Python 2.6 Interpeter:PyCharm社区版3.4 操作系统:Windows 7
答案 0 :(得分:1)
异常消息可能更清楚一点,但最后一行应为shutil.copy2(os.path.join(source, file), destination)
,以便源完全合格。
答案 1 :(得分:1)
我得到了它的工作:
import os, shutil
source = r"C:\TCR_Calgary\projects"
destination = r"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):
file_path = os.path.realpath(os.path.join(root, file))
shutil.copy2(file_path, destination)