2017-05-29 32 views
0

我想從一個文件夾複製粘貼到另一個文件使用Python Shutil模塊,並給我一個錯誤,不知道是什麼問題。Python的複製和過去

import os 
import shutil 

source = os.listdir("D:\Personal\TEST\SRC") 
print source 
destination = "D:\Personal\TEST\DEST" 

for files in source: 
    if files.endswith('.txt'): 
     shutil.copy(files,destination) 

Error: 
File "C:/Users/xxx/xxx/config/scratches/test.py", line 10, 
in <module> 
shutil.copy(files,destination) 
File "C:\Python27\Lib\shutil.py", line 119, in copy 
copyfile(src, dst) 
File "C:\Python27\Lib\shutil.py", line 82, in copyfile 
with open(src, 'rb') as fsrc: 
IOError: [Errno 2] No such file or directory: 'TEST.txt' 

任何幫助非常感謝 謝謝。

+0

似乎'listdir'返回相對路徑。 –

+0

更改'shutil.copy(文件,目的地)'爲'在文件中的文件名:shutil.copy(os.path.join(r「D:\ Personal \ TEST \ src」,文件名),目的地)' – inspectorG4dget

回答

0

試試這個:

import os 
import shutil 

source = r"D:\Personal\TEST\SRC" 
destination = r"D:\Personal\TEST\DEST" 

for file in [os.path.join(source, x) for x in os.listdir(source)]: 
    if file.endswith('.txt'): 
     shutil.copy(file, os.path.join(destination, os.path.basename(file))) 
+0

非常感謝對於答案,它按預期工作。 –

+0

@donjacob那麼請將您的答案標記爲合適的答案,以便將問題視爲*關閉*。 –