2017-01-24 81 views
5

我想使用Python將所有文本文件從一個文件夾移動到另一個文件夾。我發現這個代碼:使用Python將所有文件從一個目錄移動到另一個目錄

import os, shutil, glob 

dst = '/path/to/dir/Caches/com.apple.Safari/WebKitCache/Version\ 4/Blobs ' 
try: 
    os.makedirs(/path/to/dir/Tumblr/Uploads) # 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) 

我希望它移動在Blob文件夾中的所有文件。我沒有收到錯誤,但它也沒有移動文件。

回答

7

試試這個..

import shutil 
import os 

source = '/path/to/source_folder' 
dest1 = '/path/to/dest_folder' 


files = os.listdir(source) 

for f in files: 
     shutil.move(source+f, dest1) 
1

這應該可以做到。還請閱讀shutil模塊的documentation以選擇適合您需求的函數(shutil.copy(),shutil.copy2(),shutil.copyfile()或shutil.move())。

import glob, os, shutil 

source_dir = '/path/to/dir/with/files' #Path where your files are at the moment 
dst = '/path/to/dir/for/new/files' #Path you want to move your files to 
files = glob.iglob(os.path.join(source_dir, "*.txt")) 
for file in files: 
    if os.path.isfile(file): 
     shutil.copy2(file, dst) 
+0

但我在哪裏可以定義新txt文件的目的地? – malina

0

請看一看實現copytree功能的其中:

names = os.listdir(src)

  • 與清單目錄中的文件 個

  • 複製文件有:

    for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) copy2(srcname, dstname)

獲取dstname是沒有必要的,因爲如果目標參數指定的目錄中,該文件將使用基本文件名從複製到DST srcname

替換copy2 by move

3

將「.txt」文件從一個文件夾複製到另一個文件夾非常簡單,問題包含邏輯。唯一缺少的部分與正確的信息,如下替換:

import os, shutil, glob 

src_fldr = r"Source Folder/Directory path"; ## Edit this 

dst_fldr = "Destiantion Folder/Directory path"; ## Edit this 

try: 
    os.makedirs(dst_fldr); ## it creates the destination folder 
except: 
    print "Folder already exist or some error"; 

下面的代碼將與擴展名爲* .txt文件的文件從 src_fldr複製線dst_fldr

for txt_file in glob.glob(src_fldr+"\\*.txt"): 
    shutil.copy2(txt_file, dst_fldr); 
相關問題