python 文件备份

#coding:utf8
import zipfile,os
def backupToZip(folder):
    folder = os.path.abspath(folder)

    number = 1
    while True:
        zipFileName = os.path.basename(folder)+"_"+str(number)+".zip"
        if not os.path.exists(zipFileName):
            break
        number = number +1

    #create Zip File
    print ('creating %s ...'%(zipFileName))

    backupZip= zipfile.ZipFile(zipFileName,"w")

    #walk folder compress to zip
    for foldername,subfolders,filename in os.walk(folder):
        print('Adding files in %s...'%(foldername))
        backupZip.write(foldername)
        for filename in filename:
            newBase = os.path.basename(folder) + '_'
            print "newBase= "+newBase
            if filename.startswith(newBase) and filename.endswith('.zip'):
                print "filename: "+filename
                continue
            backupZip.write(os.path.join(foldername, filename))


    backupZip.close()
    print "Done"

backupToZip('C:\\gyarmy')

原文链接: python 文件备份 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-270.html )

发表评论

0则评论给“python 文件备份”