是否可以在 Python 中将一个文件夹压缩成多个文件?我刚刚找到了一些如何将文件夹/文件压缩到单个 zip 容器的示例。
简而言之:如何在 Python 中将一个文件夹压缩到多个 zip 部分?
最佳答案
您可以先将文件压缩成一个巨大的文件,然后再将其拆分成多个部分。经过测试,它有效。
# MAX = 500*1024*1024 # 500Mb - max chapter size
MAX = 15*1024*1024
BUF = 50*1024*1024*1024 # 50GB - memory buffer size
def file_split(FILE, MAX):
'''Split file into pieces, every size is MAX = 15*1024*1024 Byte'''
chapters = 1
uglybuf = ''
with open(FILE, 'rb') as src:
while True:
tgt = open(FILE + '.%03d' % chapters, 'wb')
written = 0
while written < MAX:
if len(uglybuf) > 0:
tgt.write(uglybuf)
tgt.write(src.read(min(BUF, MAX - written)))
written += min(BUF, MAX - written)
uglybuf = src.read(1)
if len(uglybuf) == 0:
break
tgt.close()
if len(uglybuf) == 0:
break
chapters += 1
def zipfiles(directory, outputZIP = 'attachment.zip'):
# path to folder which needs to be zipped
# directory = './outbox'
# calling function to get all file paths in the directory
file_paths = get_all_file_paths(directory)
# printing the list of all files to be zipped
print('Following files will be zipped:')
for file_name in file_paths:
print(file_name)
# writing files to a zipfile
with ZipFile(outputZIP,'w') as zip:
# writing each file one by one
for file in file_paths:
zip.write(file)
print('All files zipped successfully!')
if __name__ == '__main__':
outputZIP = 'attachment.zip'
zipfiles(directory, outputZIP)
file_split(outputZIP, MAX)
关于python - 将文件夹压缩成多个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20955556/