2015-12-30 102 views
2

我想創建一個備份程序來查找和複製所有txt文件從目錄和子目錄到另一個目錄。我是python的新手,並嘗試使用glob和shutil模塊。我將我的路徑添加到變量以使它們更易於更改。Python 3.4找到所有文件類型並複製到目錄

import os 
import shutil 

src= "C:/" 
dest= "F:/newfolder" 

src_files = os.listdir(src) 
for file in src: 
    filename = os.path.join(src, file) 
    if file.endswith(".txt"): 
     shutil.copy(file, dest) 

回答

0

您有:for file in src:你的意思是for file in src_files:

試試這個:

import glob, os, shutil 

files = glob.iglob(os.path.join(source_dir, "*.txt")) 
for file in files: 
    if os.path.isfile(file): 
     shutil.copy2(file, dest_dir) 
+0

工作,謝謝! – axxic3

0

使用此腳本。 將所有文本文件從SRC複製到dest目錄(目標是一個現有目錄)

import os, shutil 

def copy(src, dest): 
    for name in os.listdir(src): 
     pathname = os.path.join(src, name) 
     if os.path.isfile(pathname): 
      if name.endswith('.txt'): 
       shutil.copy2(pathname, dest)  
     else: 
      copy(pathname, dest) 

copy(src, dest) 

如果你需要得到相同的目錄樹,使用此:

def copy(src, dest): 
    for name in os.listdir(src): 
     pathname = os.path.join(src, name) 
     if os.path.isfile(pathname):   
      if name.endswith('.txt'): 
       if not os.path.isdir(dest): 
        os.makedirs(dest) 
       shutil.copy2(pathname, dest)  
     else: 
      copy(os.path.join(src, name), os.path.join(dest, name)) 
+0

謝謝你的回答。林不知道我在用輸出方式看你的腳本,我沒有收到你在打印功能中的任何錯誤,如果這是爲了調試我的問題。 – axxic3

+0

@ axxic3檢查我的編輯。 – Zety

+0

@ axxic3如果您發現它有用,您可以投票,請問更多...? – Zety

0

因爲Python 3.4有新的模塊pathlib它可以遍歷顯示目錄和子目錄。 一種可能的方式來做你所需要的是創建生成器,吐出所有的txt文件。迭代生成器並使用shutil進行復制。

from pathlib import Path 
import shutil 

src= "C:/" 
dest= "F:/newfolder" 

generator = (str(f) for f in Path(src).iterdir() if f.is_file() and f.suffix=='.txt') 

for item in generator: 
    shutil.copy2(item, dest) 
相關問題