python 将 \r 文本转换为 \n 以便 readlines() 按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1785233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:03:41  来源:igfitidea点击:

Convert \r text to \n so readlines() works as intended

pythonreadline

提问by greye

In Python, you can read a file and load its lines into a list by using

在 Python 中,您可以使用以下命令读取文件并将其行加载到列表中

f = open('file.txt','r')
lines = f.readlines()

Each individual line is delimited by \nbut if the contents of a line have \rthen it is not treated as a new line. I need to convert all \rto \nand get the correct list lines.

每个单独的行都由分隔,\n但如果一行的内容有,\r则不会将其视为新行。我需要全部转换\r\n并获得正确的列表lines

If I do .split('\r')inside the linesI'll get lists inside the list.

如果我在.split('\r')里面做,lines我会在列表中得到列表。

I thought about opening a file, replace all \rto \n, closing the file and reading it in again and then use the readlines()but this seems wasteful.

我想过打开一个文件,全部替换\r\n,关闭文件并再次读取它,然后使用 ,readlines()但这似乎很浪费。

How should I implement this?

我应该如何实施?

回答by Ned Deily

f = open('file.txt','rU')

This opens the file with Python's universal newline supportand \ris treated as an end-of-line.

这将打开Python的文件通用换行符支持\r被视为最终的线。

回答by hughdbrown

If it's a concern, open in binary format and convert with this code:

如果有问题,请以二进制格式打开并使用以下代码进行转换:

from __future__ import with_statement

with open(filename, "rb") as f:
    s = f.read().replace('\r\n', '\n').replace('\r', '\n')
    lines = s.split('\n')