如何在Python中使用bzip2压缩文件?(How to compress a file with bzip2 in Python?)

编程入门 行业动态 更新时间:2024-10-21 03:57:09
如何在Python中使用bzip2压缩文件?(How to compress a file with bzip2 in Python?)

这是我有的:

import bz2 compressionLevel = 9 source_file = '/foo/bar.txt' #this file can be in a different format, like .csv or others... destination_file = '/foo/bar.bz2' tarbz2contents = bz2.compress(source_file, compressionLevel) fh = open(destination_file, "wb") fh.write(tarbz2contents) fh.close()

我知道bz2.compress的第一个参数是一个数据,但这是我发现澄清我需要的简单方法。

我知道BZ2File但是,我找不到任何使用BZ2File的好例子。

Here is what I have:

import bz2 compressionLevel = 9 source_file = '/foo/bar.txt' #this file can be in a different format, like .csv or others... destination_file = '/foo/bar.bz2' tarbz2contents = bz2.compress(source_file, compressionLevel) fh = open(destination_file, "wb") fh.write(tarbz2contents) fh.close()

I know first param of bz2.compress is a data, but it's the simple way that I found to clarify what I need.

And I know about BZ2File but, I cannot find any good example to use BZ2File.

最满意答案

bz2.compress的文档说它需要数据,而不是文件名。 请尝试替换以下行:

tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)

...或者可能 :

with open(source_file, 'rb') as data: tarbz2contents = bz2.compress(data.read(), compressionLevel)

The documentation for bz2.compress for says it takes data, not a file name. Try replacing the line below:

tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)

...or maybe :

with open(source_file, 'rb') as data: tarbz2contents = bz2.compress(data.read(), compressionLevel)

更多推荐

本文发布于:2023-07-23 00:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225174.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:压缩文件   如何在   Python   compress   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!