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


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


python版本:Python3.7.1

python脚本:

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

source_path = os.path.abspath(r'源文件夹')
target_path = os.path.abspath(r'目标文件夹')
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()
   makeddir(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!')

猜你喜欢

转载自www.cnblogs.com/yong-sir/p/11655794.html