python - 在 Python 中 gzip 文件

标签 python gzip subprocess

我想用 Python 压缩一个文件。我正在尝试使用 subprocss.check_call(),但它一直失败并出现错误“OSError:[Errno 2] No such file or directory”。我在这里尝试的有问题吗?有没有比使用 subprocess.check_call 更好的压缩文件的方法?

from subprocess import check_call

def gZipFile(fullFilePath)
    check_call('gzip ' + fullFilePath)

谢谢!!

最佳答案

有一个模块gzip .用法:

如何创建压缩 GZIP 文件的示例:

import gzip
content = b"Lots of content here"
f = gzip.open('/home/joe/file.txt.gz', 'wb')
f.write(content)
f.close()

如何 GZIP 压缩现有文件的示例:

import gzip
f_in = open('/home/joe/file.txt')
f_out = gzip.open('/home/joe/file.txt.gz', 'wb')
f_out.writelines(f_in)
f_out.close()
f_in.close()

编辑:

Jace Browning's answer在 Python >= 2.7 中使用 with 显然更简洁易读,所以我的第二个片段将(并且应该)看起来像:

import gzip
with open('/home/joe/file.txt', 'rb') as f_in, gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
    f_out.writelines(f_in)

关于python - 在 Python 中 gzip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8156707/

相关文章:

python - 是否存在重载阶跃函数?

Java:HttpResponse header 从来没有 "Content-Encoding",但确实有 "Vary: Accept-Encoding"

jquery - Google CDN 未对 jquery 进行 gzip 压缩

Python:并行运行子进程

python - 无法从子进程解析 xml。Python 中的 Popen 输出

python - 如何使用 python/django 从 gmail 或 yahoo 等各种服务导入联系人

c++ - 将类型转换为 python

c# - 如何在 ASP.NET 中实现 GZip 压缩?

django - Python subprocess.Popen()在Docker容器中不起作用-在本地工作正常

python - 通过部分比较对 Python 3.3 嵌套列表中的列进行排序