使用Python实现不同目录下文件的拷贝


目标:要实现将一台计算机的共享文件夹中的文件备份到另一台计算机,如果存在同名的文件只要文件的大小和最后修改时间一致,则不拷贝该文件


python版本:Python3.7.1

python脚本:

from datetime import date,datetime
import os
import shutil
import json

source_path = os.path.abspath(r'D:\Video\540409938')
target_path = os.path.abspath(r'D:\Video\540409939')
jsonfilepath = os.path.abspath(target_path + r"\log.json")

def load():
    flag = os.path.exists(jsonfilepath)
    if flag:
        with open(jsonfilepath, 'r', encoding='utf-8') as f:
            data = json.load(f)
            if data == None:
                data = []
            return data
    else:
        with open(jsonfilepath, 'a', encoding='utf-8') as f:
            return []

def store(data):
    with open(jsonfilepath, 'w') as fw:
        json.dump(data,fw)

def makedir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)

if __name__ == '__main__':
    makedir(target_path)
    logdata = load()
        
    if os.path.exists(source_path):
        # root 所指的是当前正在遍历的这个文件夹的本身的地址
        # dirs 是一个 list,内容是该文件夹中所有的目录的名字(不包括子目录)
        # files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录)
        for root, dirs, files in os.walk(source_path):
            for file in files:
                src_file = os.path.join(root, file)
                fsize = os.path.getsize(src_file)
                fmtime = os.path.getmtime(src_file)
                log={'file':src_file,'fsize':fsize,'fmtime':fmtime}

                iscopy=0
                for item in logdata:
                    # 判断文件是否拷贝过
                    if (item["file"] == src_file and item["fsize"] == fsize and item["fmtime"] == fmtime):
                        iscopy=1
                        break
                
                if iscopy==0:
                    # 未拷贝过则拷贝到当天文件夹下
                    target = target_path + "\\" + date.today().strftime("%Y%m%d")
                    makedir(target)
                    logdata.append(log)
                    shutil.copy(src_file, target)

    store(logdata)
    print('copy files finished!')

 

posted @ 2019-10-11 17:52  沙木  阅读(618)  评论(0编辑  收藏  举报