对标准Zipfile包的改进
ruamel.std.zipfile的Python项目详细描述
package ruamel.std.zipfile是一个下拉列表 与标准Zipfile包相比的改进
您只需替换:
import zipfile
使用:
import ruamel.std.zipfile as zipfile
这个包包括InMemoryZipFile,它允许在内存中轻松创建ZIP文件, 并允许在完全创建后进行流媒体播放或写入光盘:
with InMemoryZipFile() as imz: imz.append("test.txt", "Another test").append("test2.txt", "Still another") with open('some_file.zip', 'wb') as fp: fp.write(imz.data)
它将写入一个两个文件的ZIP文件,其中第一个文件名为 test.txt包含内容Another test。.data内容可以 也可以动态返回到web浏览器等
从zip中删除文件
利用InMemoryZipFile的延迟写入,可以 函数delete_from_zip_file(file_name, pattern, file_names), 使用string或pathlib.Path作为文件名。
任何与模式匹配的文件(如果提供)都将从 文件,以及任何与file_names匹配的文件 字符串/路径,允许单个非列表实例)。
下面删除以.pth结尾的所有文件和文件 tmp/README.rst来自ZIP文件test.zip:
delete_from_zip_file('test.zip', pattern='.*.pth', file_names=['README.rst'])
或:
delete_from_zip_file('test.zip', pattern='.*.pth', file_names='README.rst')
或:
delete_from_zip_file('test.zip', pattern=re.compile('.*.pth'), file_names='README.rst')
请注意,这是一个“re”模式,而不是一个“glob”模式。 可以,但不必提供 re.compile()
重新创建并重新压缩zip文件,请考虑以下因素 删除文件时(限制处理的文件大小,合并 模式而不是多个调用)