2013-08-22 127 views
36

我學習的Python(巨蟒3)複製文件,我可以做這個蟒蛇通過通配符

import shutil 
shutil.copyfile('C:/test/test.txt', 'C:/lol/test.txt') 

1個文件複製到一個新的目錄 什麼我現在要做的是複製所有*。 TXT文件從C:/到C:/測試

* .TXT是搜索所有的文本文件我的硬盤

回答

9

使用glob.glob()上獲得的匹配文件名列表,然後遍歷一個通配符列表。

+2

該死2秒過早:d –

+0

進口shutil,glob的 dest_dir將= 「C:\\」 在glob.glob F( 「* DAT」): shutil.copy (f,dest_dir) – Johnny

48
import glob 
import shutil 
dest_dir = "C:/test" 
for file in glob.glob(r'C:/*.txt'): 
    print(file) 
    shutil.copy(file, dest_dir) 
-2

我首先使用python 2.7測試來確保它能正常工作。 我使用了通配符*,因爲我將日期添加到了所有文本文件中。 filename1_2016_04_18.txt 另外一些文本文件有不同的最終用戶附加到文本文件。 filename2_username.txt

import os, glob 

directorypath = 'C:\\Program Files\\Common Files' 
os.chdir(directorypath) 

files = ['filename1', 'filename2', 'filename3'] 
print ('A %(files)s'% vars()) 
for filename in files: 
    file1 = filename + "*" + "." + "txt"; print ('1 %(file1)s'% vars()) 
    file2 = ('%(file1)s') % vars(); print ('2 %(file2)s'% vars()) 
    file3=glob.glob(file2); print ('3 %(file3)s'% vars()) 
    for filename4 in file3: 
     try: 
      if os.path.isfile(filename4): 
        print ('I am deleteing this file %(filename4)s'% vars()) 
        os.remove(filename4) 
      else: ## Show an error ## 
        print("Error can not delete text file : %s because file not found" % filename4) 
     except OSError, e: ## if failed, report it back to the user ## 
       print ("Error: %s - %s." % (e.filename,e.strerror))