- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
with open(fn, 'rt') as f:
lines = f.readlines()
这会读取带有 LF 行结尾的 CR LF 文本文件(WinXP、Py 2.6)。所以 lines
包含 '\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()
还将文件内容解码为 unicode 值。
关于Python,使用CRLF按原样读取CRLF文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350305/
我正在尝试从 csv 文件中读取数据,而不是例如001000 我在我的数据中得到 1000。 我试过设置 as.is=!stringsAsFactors ,但收到以下错误消息: error: obj
我正在尝试实现类似于Go Playground的 share 按钮的功能。 单击名为share的按钮时,当前的HTML响应将保存到文件中。这还包括用户可以看到的所有内容。 到目前为止我可以做什么 -我
在迁移到使用git的过程中,我们获得了一个解决方案的生产版本,并将其作为master提交。 然后我们制作了一个开发版本,并创建了一个名为develop的孤立分支。 (背景:我们在这里有点纠结的原因是,
题 请建议一种去除标点符号的方法,但不是 中的那些。或 . 例如,来自:the asbestos fiber $% with 产生:the asbestos fiber unk is unusu
我正在创建一个包含所有其他程序的程序,但是当我尝试写入该文件时,它会将 \n 作为新行打印,而不是字面上的 \n . 例如: file.write("""a=input("What would you
我有一个 docker 安装,在 /var/lib/docker 中有几个图像和大约 150Gigs 的数据。此设置使用 overlayfs 作为其存储驱动程序。 /var/lib/docker/ov
我是一名优秀的程序员,十分优秀!