2016-12-01 27 views
0

基本上我想在我的腳本中執行的操作是將一些文件從dest_path複製到source_path。你可以設置它,看看它是如何工作的 -我的Python腳本在複製時忽略文件

但由於某種原因,它複製第一個文件,並告訴我其餘的已被複制,這是不正確的。有沒有我沒有看到或我做錯了?即時通訊相當新的Python很抱歉,如果我做了一些顯然是錯誤的,我只是不能看到它... ...

import time, shutil, os, datetime 

source_path = r"C:\SOURCE"        # Your Source path 
dest_path = r"C:\DESTINATION"       # Destination path 
file_ending = '.txt'         # Needed File ending 
files = os.listdir(source_path)       # defines 
date = datetime.datetime.now().strftime('%d.%m.%Y')  # get the current date 

while True: 
    print("Beginning checkup") 
    print("=================") 
    if not os.path.exists(source_path or dest_path): # checks if directory exists 
     print("Destination/Source Path does not exist!") 
    else: 
     print("Destination exists, checking files...") 
     for f in files: 
      if f.endswith(file_ending): 
       new_path = os.path.join(dest_path, date,) 
       src_path = os.path.join(source_path, f) 
       if not os.path.exists(new_path): # create the folders if they dont already exists 
        print("copying " + src_path) 
        os.makedirs(new_path) 
        shutil.copy(src_path, new_path) 
       else: 
        print(src_path + " already copied") 
        # shutil.copy(src_path, new_path) 

    print("=================") 
    print('Checkup done, waiting for next round...') 
    time.sleep(10) # wait a few seconds between looking at the directory 
+3

'如果不是os.path.exists(source_path或dest_path):'沒有做你認爲它的做法。 '或'不能這樣工作。 – user2357112

+1

如果不是'os.path.exists(new_path)',將檢查'source_path'中的每個文件,並且只有第一個文件會進入這個塊,因爲你在第一次通過 – depperm

+0

創建'new_path' new_path = os.path.join(dest_path,date,)實際上是new_path = os.path.join(dest_path,date,f),但是它會爲它複製的每個文件創建另一個文件夾。那不是我想要的,所以我刪除了f,現在它做到了。我該如何解決這個問題@deppem – diatomym

回答

1

像@ user2357112提到if not os.path.exists(source_path or dest_path)不是做你的想法。更改爲

if not os.path.exists(source_path) or not os.path.exists(dest_path): 

,因爲它在if通過創建目錄new_path第一次這樣只會複製一個文件。像這樣的東西應該工作:

if f.endswith(file_ending): 
    new_path = os.path.join(dest_path, date,) 
    src_path = os.path.join(source_path, f) 
    if not os.path.exists(new_path): # create the folders if they dont already exists 
     os.makedirs(new_path) 
    if not os.path.exists(os.path.join(new_path,f)): 
     print("copying " + src_path) 
     shutil.copy(src_path, os.path.join(new_path,f)) 
    else: 
     print(src_path + " already copied") 

如果new_path目錄不存在,則使該目錄(這應該只發生一次,這if可以在循環外移動以及new_path初始化)。在單獨的if中檢查文件是否存在於該目錄內,如果不將該文件複製到該位置,請打印您的消息。

+0

首先,非常感謝。它確實有用,謝謝你,但我沒有完全理解你是如何解決它的。你添加了另一個if語句,你能解釋給我,所以我知道代碼在做什麼?我仍然有很多工作要處理這個腳本,所以我想完全理解它在做什麼。希望你能理解,並再次感謝。 – diatomym

+0

@diatomym讓我知道如果解釋是足夠的,或者如果你需要更多 – depperm

+0

啊所以你也可以用os.path.join()檢查文件,對不對?這就是爲什麼我發現它令人困惑,但我現在認爲它很清楚。 – diatomym