如何使用Python zipfile将文件放入zip存档中

时间:2016-06-02 16:50:16

标签: python python-3.x zipfile

我写了一个python(3.5)脚本,用zip档案创建我的文件备份,效果很好。我使用Windows,我从GnuWin32为这个项目安装了zip命令。但我想改用Python的Zipfile库。我该如何修改我的代码?

import os
import time
import sys

source = 'C:\\ExampleFile'

target_directory ='D:\\BACKUP'

confirm = input("Are you sure you want to run backup? (y/n): ")

if confirm == "y":
    if not os.path.exists(target_directory):
        os.mkdir(target_directory)

    Folder = target_directory + os.sep + time.strftime('%d-%m-%Y')
    Subfolder = time.strftime('%H-%M')

    comment = input('Enter a backup comment (optional):  ')

    if len(comment) == 0:
        target = Folder + os.sep + Subfolder + '.zip'
    else:
        target = Folder + os.sep + Subfolder + '_' + comment.replace(' ', '_') + '.zip'
    if not os.path.exists(today):
        os.mkdir(Folder)
        print('Successfully created directory', Folder)

    zip_command = "zip -r {0} {1}".format(target,''.join(source))

    print("Running:")
    if os.system(zip_command) == 0:
        print('\nSuccessful backup to', target)
    else:
        print('\nBackup FAILED')

elif confirm == "n":
    sys.exit()
else:
    print("Use only 'y' or 'n'")

2 个答案:

答案 0 :(得分:1)

这可能是一个好的开始:

#!/usr/bin/python
import zipfile, os

def zipdir(path, fname="test.zip"):
    zipf = zipfile.ZipFile(fname, 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(path):
        for file in files:
            zipf.write(os.path.join(root, file))
    zipf.close()

答案 1 :(得分:0)

更改zip_command = "zip -r {0} {1}".format(target,''.join(source)) 到python zip文件。像zip_command = "zip.py -r {0} {1}".format(target,''.join(source))

这样的东西