python - 在内存流中进行编码或 TextIOBase 如何工作?

标签 python in-memory stringio cstringio

我目前正在阅读 io 模块的文档:https://docs.python.org/3.5/library/io.html?highlight=stringio#io.TextIOBase

也许是因为我对Python不够了解,但大多数情况下我只是不理解他们的文档。

我需要将addresses_list中的数据保存到csv文件中,并通过https将其提供给用户。所以所有这一切都必须发生在内存中。这是它的代码,目前运行良好。

addresses = Abonnent.objects.filter(exemplare__gt=0)
addresses_list = list(addresses.values_list(*fieldnames))

csvfile = io.StringIO()
csvwriter_unicode = csv.writer(csvfile)
csvwriter_unicode.writerow(fieldnames)

for a in addresses_list:
    csvwriter_unicode.writerow(a)
csvfile.seek(0)

export_data = io.BytesIO()
myzip = zipfile.ZipFile(export_data, "w", zipfile.ZIP_DEFLATED)
myzip.writestr("output.csv", csvfile.read())
myzip.close()
csvfile.close()
export_data.close()

# serve the file via https

现在的问题是我需要将 csv 文件的内容以 cp1252 编码,而不是 utf-8 编码。传统上,我只需编写 f = open("output.csv", "w",encoding="cp1252") ,然后将所有数据转储到其中。但对于内存中的流,它就不会这样工作了。 io.StringIO()io.BytesIO() 都不接受参数 encoding=

这是我无法理解文档的地方:

The text stream API is described in detail in the documentation of TextIOBase.

还有documentation of TextIOBase说的是:

encoding=

The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.

但是 io.StringIO(encoding="cp1252") 只是抛出:TypeError: 'encoding' 是此函数的无效关键字参数

那么如何将 TextIOBase 的 enconding 参数与 StringIO 一起使用?或者说这一般是如何运作的?我很困惑。

最佳答案

StringIO 仅处理字符串/文本。它不知道有关编码或字节的任何信息。做你想做的事情的最简单方法可能是这样的:

f = StringIO()
f.write("Some text")

# Old-ish way:
f.seek(0)
my_bytes = f.read().encode("cp1252")

# Alternatively
my_bytes = f.getvalue().encode("cp1252")

关于python - 在内存流中进行编码或 TextIOBase 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47309512/

相关文章:

python - 为什么 json.dumps 使用 "\uxxxx"转义非 ascii 字符

python - 将字符串结构转换为另一个字符串结构

python - 根据多个值过滤 numpy 结构化数组

内存中的 MongoDB 索引与分片

ruby - 与 String 相比,在 Ruby 中使用 StringIO 有什么优势?

python - tilestache Provider() 图层对象?可以获取引用URL吗?

.net - 在调试器下运行时更改程序流程

java - 查找部分属性

python - pysftp putfo 在 SFTP 服务器上创建一个空文件,但不传输来自 StringIO 的内容

python - 使用 read_csv 转换 StringIO 时使用 Pandas 的奇怪输出