Python 文件復制轉移


參考鏈接

說明

下面先是 對比文件名和大小是否一致,不一致則替換。目標文件夾沒有則直接拷貝
並且在目標文件夾追加了一個log.txt日志

import shutil
import os
import time

# sourcefile:源文件路徑 fileclass:源文件夾 destinationfile:目標文件夾路徑
def copy_file(sourcefile, destinationfile,logTxt=""):
    logTxt=(logTxt,os.path.join(destinationfile, "log.txt"))[len(logTxt)==0];
    # 遍歷目錄和子目錄
    for filenames in os.listdir(sourcefile):
        # 取得文件或文件名的絕對路徑,  os.path.join 把目錄和文件名合成一個路徑
        filepath = os.path.join(sourcefile, filenames)
        # 判斷是否為文件夾
        if os.path.isdir(filepath):
            copy_file(filepath, destinationfile + '/' + filenames,logTxt)
        # 判斷是否為文件
        elif os.path.isfile(filepath):
            #  print('Copy %s'% filepath +' To ' + destinationfile)
         # 如果無文件夾則重新創建
            if not os.path.exists(destinationfile):
                os.makedirs(destinationfile)
            # 判斷是否存在文件,且文件大小一致
            destinationfilePath = os.path.join(destinationfile, filenames)
            # 判斷是否存在文件
            if os.path.exists(destinationfilePath):
                # 對比文件大小和文件名,如果不一致則替換
                if not (os.path.basename(filepath)==os.path.basename(destinationfilePath) and os.path.getsize(filepath)==os.path.getsize(destinationfilePath)) :
                    writeTxt(logTxt,filepath+"\t與\t"+destinationfilePath + "  不相同,將替換")
                    print(logTxt,filepath+"\t與\t"+destinationfilePath + "  不相同,將替換")
                    shutil.copy(filepath, destinationfile)
            else:
                writeTxt(logTxt,filepath+"\t與\t"+destinationfile+"  無相同文件,則拷貝")
                print(logTxt,filepath+"\t與\t"+destinationfile+"  無相同文件,則拷貝")
                shutil.copy(filepath, destinationfile)
        
def writeTxt(path,message):
    with open(path,'a') as f:    # a是追加,如果不存在則創建文件
        f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"\t"+message+'\n')  

copy_file("D:/old", "D:/new","D:/new/log.txt")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM