如何在python中只读取带有readlines的回车符?

use*_*050 6 python newline carriage-return

我有一个包含一个文本文件\n,并\r\n结束行标志.我想只拆分\r\n,但无法想出用python的readlines方法做到这一点的方法.有一个简单的解决方法吗?

Luk*_*raf 10

正如@eskaev所提到的,如果没有必要,你通常会希望避免将完整的文件读入内存.

io.open()允许您指定newline关键字参数,因此您仍然可以遍历行并使它们在指定的换行符处拆分:

import io

for line in io.open('in.txt', newline='\r\n'):
    print repr(line)
Run Code Online (Sandbox Code Playgroud)

输出:

u'this\nis\nsome\r\n'
u'text\nwith\nnewlines.'
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,`io.open`是Python 3内置的`open`函数.您只需要在Python 2的`io`模块中查找它. (5认同)

jte*_*y14 0

不使用 readline,只需使用 read 和 split。

例如

with open('/path/to/file', 'r') as f:
    fileContents = f.read() #read entire file
    filePieces = fileContents.split('\r\n')
Run Code Online (Sandbox Code Playgroud)