我正在嘗試編寫一個簡短的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社區版3.4 操作系統:Windows 7
謝謝!這對我來說不太合適(因爲要複製的文件在源文件中的子文件夾中),但它確實指向了正確的方向。 –