gpt4 book ai didi

python - 如何使用 python 将 ascii 编码的换行符写入文件

转载 作者:行者123 更新时间:2023-11-28 20:12:31 24 4
gpt4 key购买 nike

我认为这应该可行:

file = open('filename.ppm', 'wb')
file.write('upper\nlower'.encode(encoding='ascii'))

当我运行代码时,虽然没有换行符;filename.pmm 使用记事本打开时包含“upperlower”。

最佳答案

open()中指定编码:

>>> with open("filename.ppm", "w", encoding="ascii") as f:
... f.write("upper\nlower")

$ cat filename.ppm
upper
lower $

open() 的文档函数可能有几条线索可以说明为什么您当前的方法会给您带来意想不到的结果。

首先,关于换行符和\n\r\n:

When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

我的猜测是,在您的情况下,因为您正在将 bytes 写入输出流,所以在将“原始”字节写入文件时可能不会发生转换。

最后一件事值得一提的是 encoding="ascii" 的使用。在这种情况下,这实际上并不重要,因为 ASCII 是 Unicode 的一个子集,您的所有字符都在 ASCII 范围内。

>>> all(i.isascii() for i in "upper\nlower")
True

关于python - 如何使用 python 将 ascii 编码的换行符写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com