Python基于SHA256码备份数据,重复数据只备份一次

通过该代码,去除重复备份的数据,减少存储空间浪费

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import os

import datetime

import platform

import sys

import shutil

import  hashlib

def mkdir(path):

# 引入模块

    import os

# 去除首位空格

    path = path.strip()

# 去除尾部 \ 符号

    #path = path.rstrip("\\")

    # 判断路径是否存在

# 存在    True

# 不存在  False

    isExists = os.path.exists(path)

# 判断结果

    if not isExists:

# 如果不存在则创建目录

        # 创建目录操作函数

        try:

os.makedirs(path)

except:

return False

        print(path +" create successed!")

return True

    else:

# 如果目录存在则不创建,并提示目录已存在

        print(path +"is exist!")

return True

def CalcFileSha256(filname):

''' calculate file sha256 '''

    bufsize =1024 *1024 *16

    with open(filname,"rb")as f:

sha256obj = hashlib.sha256()

while True:

data = f.read(bufsize)

if data  ==None or len(data) ==0:

break

            sha256obj.update(data)

hash_value = sha256obj.hexdigest()

return hash_value

class CoSailTextFile():

def __init__(self, filename =None):

self.filename = filename

self.f =None

    def open(self, m):

try:

self.f =open(self.filename, m)

except Exception as e:

print(e)

self.f =None

return False

return True

    def writeLine(self, line):

try:

self.f.write(line +"\n")

return True

        except Exception as  e:

print(e)

return False

    def writeLines(self, lines):

for linein lines:

if self.writeLine(line) ==False:

return False

return True

    def readLine(self):

text =None

        try:

text =self.f.readline()

except Exception as e:

print(e)

return None

        return text

def readAll(self):

return self.f.read()

def readLines(self):

return self.f.readlines()

def close(self):

if self.f !=None:

try:

self.f.close()

self.f =None

            except Exception as e:

print(e)

return False

return True

return True

    def isOpen(self):

return self.f !=None

def getFilePathExtend(fileName):

filePath, suffix = os.path.splitext(fileName)

filePath = os.path.dirname(fileName)

l =len(suffix)

fileName = os.path.split(fileName)[1]

return filePath,  suffix[1:l +1], fileName

filesdict = {}

def scansamenamefile(path, type="filename"):

"""

    扫描目录内重复文件,

    :param path: 扫描路径

    :param type: 相同文件判别方式,"filename" : 文件名  "sha256":sha256码

    :return:

"""

    if os.path.exists(path) ==False:

print("Store Path :" + path +" isn't exist!")

return None

    try:

files = os.listdir(path)

except FileNotFoundError:

print("File Not FoundError")

return None

    for fiin files:

# file full path

# sleep 1

# time.sleep(1)

        fi_d = os.path.join(path, fi)

samefilelist =None

        # is directory

        if os.path.isdir(fi_d):

if os.path.islink(fi_d):

continue

            """ recursion"""

            scansamenamefile(fi_d, type)

# print("dir = ", fi_d)

# is file

        else:

file_path, suffix, file_name = getFilePathExtend(fi_d)

tmpfullpath = file_path +"/" + file_name

samekey =""

            sha256 = CalcFileSha256(tmpfullpath)

if type =="filename":

samekey = file_name

if type =="sha256":

samekey = sha256

try:

samefilelist = filesdict[samekey]

except Exception as e:

print(e)

samefilelist =None

            if samefilelist ==None:

samefilelist = []

filesdict[samekey] = samefilelist

fileattrdict = {}

fileattrdict["filepath"] = tmpfullpath

fileattrdict["size"] = os.path.getsize(tmpfullpath)

fileattrdict["sha256"] = CalcFileSha256(tmpfullpath)

fileattrdict["filename"] = file_name

samefilelist.append(fileattrdict)

return filesdict

def statallfiles(d):

v =0;

o =None

    for kin d:

o = d[k]

v +=len(o)

return v

def statsamenamefiles(d):

v =0;

o =None

    for kin d:

o = d[k]

if len(o) >=2:

v +=1

    return v

def outduplicatefilemsg(d, textFile):

v =0;

o =None

    textFile.writeLine("")

textFile.writeLine("**************Duplicate file list*****************")

for kin d:

o = d[k]

if len(o) >=2:

textFile.writeLine("")

txt ="file name : " + o[0]["filename"] +" sha256 : " +o[0]["sha256"] +" Duplicate : " +str(len(o))

textFile.writeLine(txt)

txt ="file list :"

            for objin o:

txt ="fileputh :" + obj["filepath"] +" size : " +str(obj["size"]) +" SHA256 = " + obj["sha256"]

textFile.writeLine(txt)

def outonefilemsg(d, textFile):

v =0;

o =None

    textFile.writeLine("")

textFile.writeLine("**************Unique file list*****************")

for kin d:

o = d[k]

if len(o) ==1:

for objin o:

txt ="fileputh :" + obj["filepath"] +" size : " +str(obj["size"])

textFile.writeLine(txt)

def statpathfileattr(pathlistfilename, logpath,  type="filename"):

"""

    :param pathlistfilename:  要统计的文件目录列表名,每行一个目录

    :param logpath 日志文件路径

    :return:

"""

    """

"""

    if logpathis None:

"""

        如果日志路径为空,则以输入文件列表路径为日志存储路径"""

        logpath, _, _= getFilePathExtend(pathlistfilename)

if os.path.exists(pathlistfilename) ==False:

print("path list filename isn't exist!")

return

    if os.path.exists(logpath) ==False:

print("log path isn't exist")

return

    f = CoSailTextFile(pathlistfilename)

f.open("r")

lines = f.readLines()

for linein lines:

line = line.strip('\n')

statpathfileattrbypath(line, logpath, type)

f.close()

def backuppathfile(pathlistfilename, descpath, type="filename"):

"""

    :param pathlistfilename:  备份文件列表中指定目录到目的目录

    :param descpath 备份目的mulu

    :return:

"""

    """

"""

    if os.path.exists(descpath) ==False:

print("backup descpath isn't exist")

return

    if os.path.exists(pathlistfilename) ==False:

print("path list filename isn't exist!")

return

    f = CoSailTextFile(pathlistfilename)

f.open("r")

lines = f.readLines()

for linein lines:

line = line.strip('\n')

d = scansamenamefile(line, type)

if d ==None:

continue

        backupfiletodest(descpath, line, d)

f.close()

def statpathfileattrbypath(path, logpath,  type="filename"):

"""

    统计指定路径的文件数量以及重复文件,并输出统计信息

    :param path: 要统计的路径

    :param logpath: 统计信息存储路基

    :return:

"""

    d = scansamenamefile(path, type)

if d ==None :

return

    print("allfiles", statallfiles(d))

print("sameallfiles", statsamenamefiles(d))

t = path.replace("/","-");

t = t.replace("\\","-");

t = t.replace(":","")

if (platform.system() =='Windows'):

pass

    elif (platform.system()=='Linux'):

t = t[1:]

lonfilename = logpath +"/" + t + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') +".log"

    lonfilename = lonfilename.replace("//","/")

f = CoSailTextFile(lonfilename)

f.open("w")

f.writeLine("stat path : " + path)

f.writeLine("all files : " +str(statallfiles(d)))

f.writeLine("Duplicate files : " +str(statsamenamefiles(d)))

outduplicatefilemsg(d, f)

outonefilemsg(d, f)

f.close()

def backupfiletodest(destpath, sourcepath, filedict=None):

"""

    从原路径中拷贝文件

    :param destpath: 备份目的目录

    :param sourcepath:要备份的目录

    :param filedict:要备份目录中文件字典

    :return:

"""

    for keyin filedict:

obj = filedict[key]

if len(obj) ==0:

continue

        fileattr = obj[0]

filefullpath = fileattr["filepath"]

tmp,_, filename = getFilePathExtend(filefullpath)

#tmp = filefullpath.replace(sourcepath, "")

#if (platform.system() == 'Windows'):

        tmp = tmp.replace(sourcepath,"")#tmp.replace(sourcepath[0:2], "")

        destfullpath = destpath + tmp#os.path.join(destpath, tmp)

        destfullpath = destfullpath.replace("//","/")

if os.path.exists(destfullpath) ==False:

mkdir(destfullpath)

try:

shutil.copyfile(filefullpath, os.path.join(destfullpath, filename))

except Exception as e:

print(e)

if __name__ =='__main__':

filesdict.clear()

filesdict={}

argv = sys.argv

print(argv)

"""

if (len(argv) == 3):

statpathfileattr(argv[1], argv[2])

elif (len(argv) == 2):

statpathfileattr(argv[1], None)

else:

statpathfileattr("E:/1.txt", "E:/")

"""

"""

    "E:/1.txt" : 目录列表

    E:/wiredtirge :备份目的目录    "sha256" : 文件拷贝类型,按sha256 码, 或"filename" 文件名

"""

    backuppathfile("E:/1.txt","E:/wiredtirge","sha256")

#backupfiletodest("E:/wiredtirge", "E:/data",filesdict )

    print(type(CalcFileSha256("E:/gsl2.4.zip")))

sha2561 =CalcFileSha256("E:/gsl2.4.zip")

sha2562 = CalcFileSha256("E:/1.txt")

if (sha2561 == sha2562):

print("true")

print(sha2562)

print(sha2561)

#d = buildfilenamedictformfilelist("/home/hadoop/tmp/dir-and-files.list")

    """存储目的路径根目录"""

"""

destrootpath = "/home/hadoop/tmp4"

path = "E:/data"

d =  scansamenamefile(path)

print(d)

for k in d:

print("key =", k)

print("files = ", len(d[k]))

print("allfiles", statallfiles(d))

print("sameallfiles", statsamenamefiles(d))

f = CoSailTextFile("e:/sss.log")

f.open("w")

f.writeLine("stat path : " + path)

f.writeLine("all files : " + str(statallfiles(d)))

f.writeLine("Duplicate files : " +str(statsamenamefiles(d)))

outduplicatefilemsg(d, f)

outonefilemsg(d, f)

f.close()

f = CoSailTextFile("E:/1.txt")

f.open("r")

text = f.readLines()

print((text))

"""

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,165评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,503评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,295评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,589评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,439评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,342评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,749评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,397评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,700评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,740评论 2 313
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,523评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,364评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,755评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,024评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,297评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,721评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,918评论 2 336

推荐阅读更多精彩内容