zoukankan      html  css  js  c++  java
  • 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+"	与	"+destinationfilePath + "  不相同,将替换")
                        print(logTxt,filepath+"	与	"+destinationfilePath + "  不相同,将替换")
                        shutil.copy(filepath, destinationfile)
                else:
                    writeTxt(logTxt,filepath+"	与	"+destinationfile+"  无相同文件,则拷贝")
                    print(logTxt,filepath+"	与	"+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())+"	"+message+'
    ')  
    
    copy_file("D:/old", "D:/new","D:/new/log.txt")
    
    
  • 相关阅读:
    继承性03
    继承性
    Arrays与Math类
    Static关键字
    random模块,time模块,os模块,sys模块
    re模块
    冒泡排序、递归、二分查找
    内置函数
    生成器和生成器表达式
    迭代器
  • 原文地址:https://www.cnblogs.com/Alex-Mercer/p/12723573.html
Copyright © 2011-2022 走看看