>  기사  >  백엔드 개발  >  파이썬 백업 파일

파이썬 백업 파일

巴扎黑
巴扎黑원래의
2016-12-09 09:48:491267검색

작업:

특정 수정으로 인해 실수로 편집 결과가 지워지는 것을 방지하기 위해 특정 디렉터리 트리에서 수정된 파일을 여러 번 백업하려고 합니다. 다음 Python 스크립트를 주기적으로 실행하여 지정된 디렉터리의 파일을 백업합니다.

#-*- coding:utf-8 -*-
import sys,os,shutil,filecmp
MAXVERSIONS = 100
def backup(tree_top, bakdir_name="bakdir"):
for dir,subdirs,files in os.walk(tree_top):
#确保每个目录都有一个备份目录
backup_dir = os.path.join(dir,bakdir_name)
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
#停止对备份目录的递归
subdirs[:] = [d for d in subdirs if d != bakdir_name]
for file in files:
filepath = os.path.join(dir,file)
destpath = os.path.join(backup_dir,file)
#检查以前的版本是否存在
for index in xrange(MAXVERSIONS):
backfile = '%s.%2.2d' % (destpath, index)
if not os.path.exists(backfile):
break
if index > 0:
old_backup = '%s.%2.2d' % (destpath,index-1)
abspath = os.path.abspath(filepath)
try:
if os.path.isfile(old_backup) and filecmp.cmp(abspath, old_backup,shallow=False):
continue
except OSError:
pass
try:
shutil.copy(filepath,backfile)
except OSError:
pass
if __name__ == '__main__':
try:
tree_top = sys.argv[1]
except IndexError:
tree_top = '.'
backup(tree_top)

특정 접미사가 있는 파일을 백업하려면(또는 특정 확장자를 제외한 파일을 백업하려면) for file in files 루프에 적절한 테스트를 추가하세요.

for file in files:
    name,ext = os.path.splitext(file)
    if ext not in ('.py','.txt','.doc'):
        continue

os.walk가 백업할 하위 디렉터리로 반복되는 것을 방지하려면 다음 코드에 주의하세요. os.walk 반복이 시작되면 os.walk는 하위 디렉터리를 기반으로 하위 디렉터리를 반복합니다. os.walk에 대한 이 세부 정보는 생성기 사용의 훌륭한 예이기도 하며, 생성기가 반복 코드에서 정보를 얻는 방법과 이것이 반복에 어떻게 영향을 미치는지 보여줍니다.

subdirs[:] = [d for d in subdirs if d != bakdir_name]


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.