2012-07-28 119 views
3

我有一個文件夾包含幾個文本文件。我將如何去使用python來製作這些文件的每個人的副本,並將副本放在一個新的文件夾中?將幾個文件複製到新文件夾中

+2

你到目前爲止嘗試過什麼?當我們知道您到目前爲止所做的工作時,幫助起來會更容易。 – Levon 2012-07-28 00:44:58

回答

1

我建議看這個帖子:How do I copy a file in python?

ls_dir = os.listdir(src_path)  
for file in ls_dir: 
    copyfile(file, dest_path) 

應該這樣做。

+1

'os.system'不鼓勵; 'subprocess.call'是推薦的替代方法:http://docs.python.org/library/subprocess#replacing-os-system – Tshepang 2012-07-28 01:05:46

+1

在這種情況下,兩者都不應該使用。 Python可以讀取一個很好的目錄列表(以一種處理文件名空白的方式)。 'os.listdir()' – jordanm 2012-07-28 02:06:28

+0

謝謝你的反饋@Tshepang和jordanm。我相應地更新了我的建議答案。 – cloksmith 2012-07-29 05:34:01

0

使用shutil.copyfile

import shutil 
shutil.copyfile(src, dst) 
2
import shutil 
shutil.copytree("abc", "copy of abc") 

來源:docs.python.org

2

可以使用水珠模塊來選擇您的.txt文件:

import os, shutil, glob 

dst = 'path/of/destination/directory' 
try: 
    os.makedirs(dst) # create destination directory, if needed (similar to mkdir -p) 
except OSError: 
    # The directory already existed, nothing to do 
    pass 
for txt_file in glob.iglob('*.txt'): 
    shutil.copy2(txt_file, dst) 

glob模塊只包含2功能:globiglobsee documentation)。根據Unix shell使用的規則,它們都找到與指定模式匹配的所有路徑名,但glob.glob返回一個列表,glob.iglob返回一個生成器。

+0

'makedirs(dst)'如果目的地已經存在,則失敗,不像'mkdir -p' – 2016-01-26 01:18:57

+0

好。我添加了異常處理。 – 2016-03-03 12:56:11

相關問題