首页 > 编程语言 > 详细

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

时间:2019-10-11 18:03:27      阅读:97      评论:0      收藏:0      [点我收藏+]

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


python版本:Python3.7.1

python脚本:

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

source_path = os.path.abspath(r\\192.168.1.115\md5)
target_path = os.path.abspath(rD:\Video\540409939)
jsonfilepath = os.path.abspath(target_path + r"\log.json")

def load():
    with open(jsonfilepath,r) as f:
        data = json.load(f)
        return data

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__:
    logdata = load()
        
if not os.path.exists(target_path):
    os.makedirs(target_path)

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!)

 

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

原文:https://www.cnblogs.com/yong-sir/p/11655794.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!