我想用 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/