如何使用 Python zipfile 将文件放入 zip 存档
How to put files in a zip archive using Python 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'")
这可能是一个好的开始:
#!/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()
改变zip_command = "zip -r {0} {1}".format(target,''.join(source))
到 python 压缩文件。类似于 zip_command = "zip.py -r {0} {1}".format(target,''.join(source))
我编写了一个 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'")
这可能是一个好的开始:
#!/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()
改变zip_command = "zip -r {0} {1}".format(target,''.join(source))
到 python 压缩文件。类似于 zip_command = "zip.py -r {0} {1}".format(target,''.join(source))