Home Backend Development Python Tutorial Detailed explanation and examples of Python recursive functions

Detailed explanation and examples of Python recursive functions

Feb 11, 2017 pm 01:25 PM

这篇文章主要介绍了Python 实现文件的全备份和差异备份详解的相关资料,需要的朋友可以参考下

Python实现文件的全备份和差异备份

之前有写利用md5方式来做差异备份,但是这种md5方式来写存在以下问题:

  • md5sum获取有些软连接的MD5值存在问题

  • 不支持对空目录进行备份,因为md5sum无法获取空目录的md5值

  • 权限的修改md5sum无法判断

解决方案:

利用文件的mtime ctime

mtime(Modified time)是在写入文件时随文件内容的更改而更改的

ctime(Create time)是在写入文件、更改所有者、权限或链接设置时随Inode的内容更改而更改的

废话不多说直接上代码:

#!/usr/bin/env python
import time,os,sys,cPickle
fileInfo = {}
def logger(time,fileName,status,fileNum):
  f = open('backup.log','a')
  f.write("%s\t%s\t%s\t\t%s\n" % (time,fileName,status,fileNum))
def tar(sDir,dDir,fileNum):
  command = "tar zcf %s %s >/dev/null 2>&1" % (dDir + ".tar.gz",sDir)
  if os.system(command) == 0:
    logger(time.strftime('%F %X'),dDir + ".tar.gz",'success',fileNum)
  else:
    logger(time.strftime('%F %X'),dDir + ".tar.gz",'failed',fileNum)
def fullBak(path):
  fileNum = 0
  for root,dirs,files in os.walk(path):
    for name in files:
      file = os.path.join(root, name)
      mtime = os.path.getmtime(file)
      ctime = os.path.getctime(file)
      fileInfo[file] = (mtime,ctime)
      fileNum += 1
  f = open(P,'w')
  cPickle.dump(fileInfo,f)
  f.close()
  tar(S,D,fileNum)
def diffBak(path):
  for root,dirs,files in os.walk(path):
    for name in files:
      file = os.path.join(root,name)
      mtime = os.path.getmtime(file)
      ctime = os.path.getctime(file)
      fileInfo[file] = (mtime,ctime)
  if os.path.isfile(P) == 0:
    f = open(P,'w')
    f.close()
  if os.stat(P).st_size == 0:
    f = open(P,'w')
    cPickle.dump(fileInfo,f)
    fileNum = len(fileInfo.keys())
    f.close()
    print fileNum
    tar(S,D,fileNum)
  else:
    f = open(P)
    old_fileInfo = cPickle.load(f)
    f.close()
    difference = dict(set(fileInfo.items())^set(old_fileInfo.items()))
    fileNum = len(difference)
    print fileNum
    difference_file = ' '.join(difference.keys())
    print difference_file
    tar(difference_file,D,fileNum)
    f = open(P,'w')
    cPickle.dump(fileInfo,f)
    f.close()
def Usage():
  print '''
    Syntax: python file_bakcup.py pickle_file model source_dir filename_bk
      model: 1:Full backup 2:Differential backup
    example: python file_backup.py fileinfo.pk 2 /etc etc_$(date +%F)
      explain: Automatically add '.tar.gz' suffix
  '''
  sys.exit()
if len(sys.argv) != 5:
  Usage()
P = sys.argv[1]
M = int(sys.argv[2])
S = sys.argv[3]
D = sys.argv[4]
if M == 1:
  fullBak(S)
elif M == 2:
  diffBak(S)
else:
  print "\033[;31mDoes not support this mode\033[0m"
  Usage()
Copy after login

测试:

$ python file_backup.py data.pk 1 data data_$(date +%F) #全备份
$ > data/www.linuxeye.com #测试创建文件,修改文件权限
$ chmod 777 data/py/eshop_bk/data.db
$ python file_backup.py data.pk 2 data data_$(date +%F)_1 #备份改变的文件
2
data/py/eshop_bk/data.db data/www.linuxeye.com
Copy after login

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多Python 递归函数详解及实例相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles