gpt4 book ai didi

Python,使用CRLF按原样读取CRLF文本文件

转载 作者:太空狗 更新时间:2023-10-29 18:20:27 25 4
gpt4 key购买 nike

with open(fn, 'rt') as f:
lines = f.readlines()

这会读取带有 LF 行结尾的 CR LF 文本文件(WinXP、Py 2.6)。所以 lines 包含 '\n' 结尾。如何按原样获取行:

  • 对于 CRLF 文件,获取以 '\n\r' 结尾的行
  • 对于 LF 文件,获取以 '\n' 结尾的行

最佳答案

代替内置的open() 函数,使用io.open() .这使您可以更好地控制如何使用 newline 参数处理换行符:

import io

with io.open(fn, 'rt', newline='') as f:
lines = f.readlines()

newline 设置为空字符串,启用通用换行支持,但返回未翻译的行尾;您仍然可以使用 .readlines() 来查找以任何合法的行终止符终止的行,但返回的数据与在文件中找到的数据完全相同:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated.

强调我的。

这与以二进制模式打开文件不同,在二进制模式下,.readlines() 只会在 \n 字符处拆分文件。对于具有 \r 行尾或混合行尾的文件,这意味着行不会被正确分割。

演示:

>>> import io
>>> open('test.txt', 'wb').write('One\nTwo\rThree\r\n')
>>> open('test.txt', 'rb').readlines()
['One\n', 'Two\rThree\r\n']
>>> io.open('test.txt', 'r', newline='').readlines()
[u'One\n', u'Two\r', u'Three\r\n']

请注意,io.open() 还将文件内容解码为 un​​icode 值。

关于Python,使用CRLF按原样读取CRLF文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350305/

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