2017-06-13 67 views
-1

我想從一個目錄複製具有特定文件擴展名的文件並放入另一個目錄。我嘗試搜索並發現與im相同的代碼,但它看起來沒有做任何事情,任何幫助都會很棒。在Python中複製文件

import shutil 
import os 
source = "/tmp/folder1/" 
destination = "/tmp/newfolder/" 
for files in source: 
    if files.endswith(".txt"): 
     shutil.move(files,destination) 
+0

除了這個,你可以有多個目的地,如果我想複製相同的文件到兩個不同的目錄? – gcmtb

回答

0

我認爲問題在於你的循環。您實際上在循環查找字符串「tmp/folder1 /」而不是循環查看文件夾中的文件。你的for循環所做的是逐字符串(t,m,p等)。

你想要的是循環在源文件夾中的文件列表。這是如何描述的:How do I list all files of a directory?

去那裏,你可以運行文件名,測試它們的擴展名,並像你顯示的那樣移動它們。

+0

多數民衆贊成正是我所得到的,感謝您的鏈接,缺少os.listdir,將其添加到源代碼並且工作正常:-) – gcmtb

0

你的「for源文件」從字符串「source」中選擇一個接一個字符(for不知道源是一個路徑,對於他來說它只是一個基本的str對象)。

你必須使用os.listdir:

import shutil 
import os 

source = "source/" 
destination = "dest/" 
for files in os.listdir(source): #list all files and directories 
    if os.path.isfile(os.path.join(source, files)): #is this a file 
     if files.endswith(".txt"): 
      shutil.move(os.path.join(source, files),destination) #move the file 

os.path.join來加入目錄和文件名(有一個完整的路徑)。