python - 将文本写入 gzip 文件

标签 python python-3.x file gzip

按照博客和此处其他线程中的教程和示例,写入 .gz 文件的方法似乎是以二进制模式打开它并按原样写入字符串:

import gzip
with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!')

我试过了,得到了以下异常:

  File "C:\Users\Tal\Anaconda3\lib\gzip.py", line 258, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

所以我尝试以文本模式打开文件:

import gzip
with gzip.open('file.gz', 'w') as f:
    f.write('Hello world!')

但是我得到了同样的错误:

  File "C:\Users\Tal\Anaconda3\lib\gzip.py", line 258, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

如何在 Python3 中解决这个问题?

最佳答案

mode='wb'

当写入以二进制模式打开的文件时,您必须写入字节,而不是字符串。使用 str.encode 对您的字符串进行编码:

with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!'.encode())

mode='wt'

(由 OP 找到)或者,您可以在 wt(显式 text)模式下打开文件时将字符串写入文件:

with gzip.open('file.gz', 'wt') as f:
    f.write('Hello world!')

documentation有几个方便的使用示例。

关于python - 将文本写入 gzip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49286135/

相关文章:

python - 自定义 y 标签)使用 matlibplot

python - 在字符串比较中整合通配符

c++ - 将文件的元素加载到 C++ 中的二维数组中

Javascript/AJAX/使用 JSON 发送到服务器文本和文件

python - 使用SST框架,如何通过css类或xpath点击链接?

python - 在 Python 中合并两个 GEOJSON 多边形

python - 在 python 上求解复杂的隐式方程

python - np.random.seed(1) 和 np.random.seed(0) 之间的区别?

python - 从文件输入 numpy 数组

Python "FileHandler"到 Azure Blob 存储 - 没有这样的事情吗