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

2024-06-01 10:05:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得这应该行得通:

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

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


Tags: 代码asciiopenfilenameupperencodingencodefile
3条回答

当您以二进制模式('wb')写入文件时,Python会精确地写入您提供的字节。因此,如果您编写'foo\nbar',这就是写入磁盘的内容—即使在运行代码的平台上,'\n'没有被识别为换行标记。在

如果以text模式('w')写入文件,Python将convert'\n'为运行代码的平台相应的换行标记,只要不设置newline参数:

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.

Windows使用\r\n表示新行,而Linux只使用\n。添加\r回车键以查看记事本中的换行符。在

file.write('upper\r\nlower')

指定open()中的编码:

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

$ cat filename.ppm
upper
lower $

^{}函数的文档可能有一些线索,说明为什么当前方法会给您带来意想不到的结果。在

首先,关于换行符和\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.

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

最后值得一提的是encoding="ascii"的用法。在本例中,这并不重要,因为ASCII是Unicode的一个子集,所有字符都在ASCII范围内。

^{pr2}$

相关问题 更多 >