天天看點

學習筆記《Python程式設計快速上手》實踐 9.8.1 選擇性拷貝

作者:ERIC學Python

9.8.1 選擇性拷貝

編寫一個程式,周遊一個目錄樹,查找特定擴充名的檔案(諸如.pdf 或.jpg).不論這些檔案的位置在哪裡,将它們拷貝到一個新的檔案夾中.

實踐分析:

1.需要确認目标檔案夾是否存在,如不存在建立。

2.目标目錄與工作目錄是否為同一個,正常應該不會出現這個情況。但是還是需要使用者确認,說不定想把子目錄的檔案全搬過來。

3.如果目标目錄是目前目錄的子目錄,掃描的時候也會把他掃描進去。加個判斷,是的話直接跳過。

4.不知道有沒有專用的擴充名擷取函數。想到了幾個辦法:

A.用 file.endswitch("txt") ,太麻煩需要把所有的字尾都寫一遍.直接放棄

B.用 file[-4:] in ext 來判斷,但是字尾名有長有短,比如 .py 和 .ipynb 也放棄

C.最後用了 file.splite(".")[-1] 來擷取最後一個dotall後面的文字。

5.在目标目錄中是否存在同名檔案,加入到repeat_files清單。

代碼如下:

# 9.8.1 選擇性拷貝
# 編寫一個程式,周遊一個目錄樹,查找特定擴充名的檔案(諸如.pdf 或.jpg).
# 不論這些檔案的位置在哪裡,将它們拷貝到一個新的檔案夾中.
import os
import shutil
repeat_files = []
copyed_files = []

def check_dirs(start_path, target_path):
    if not os.path.exists(start_path):
        print("工作目錄不存在,請确認!!")
        return False
    elif start_path == target_path:
        user_check = input("工作目錄與目标目錄相同,确認輸入 YES !!")
        if user_check != "YES":        
            return False
        else:
            return True
    else:
        if not os.path.exists(target_path):
            os.mkdir(target_path)        
        # return os.path.abspath(start_path), os.path.abspath(target_path)
        return True
    
def check_file_extension_name(file,extension_name):
    ext = [ext for ext in extension_name]
    if file.split(".")[-1] in ext:
        return True
    else:
        return False

def  check_file_in_target_path(file,target_path):
    if os.path.exists(os.path.join(target_path,file)):
        return True
    else:
        return False

def copy_files(start_path, target_path,extension_name):        
    if check_dirs(start_path, target_path):
        for root,subdirs,files in os.walk(start_path): 
            if root == target_path:
                print("目标目錄也在掃描範圍内,已自動忽略")
                continue
            else:      
                for file in files:
                    if check_file_extension_name(file,extension_name):
                        if check_file_in_target_path(file,target_path):
                            repeat_files.append(file)                                
                        elif not check_file_in_target_path(file,target_path):
                            shutil.copy(os.path.join(root,file),target_path)
                            copyed_files.append(file)
    return copyed_files,repeat_files


                        
start_path = ".\\"
target_path = ".\\copy"
extension_name ="jpg","png","mp3","py"
# extension_name ="txt","py"

if __name__ == "__main__":
    copy_files(start_path, target_path,extension_name)
    # print("已經完成複制的檔案:\n",copyed_files)
    print("目标目錄下重名檔案:\n",repeat_files)