Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将\r文本转换为\n以便readlines()按预期工作_Python_Readline - Fatal编程技术网

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

Python 将\r文本转换为\n以便readlines()按预期工作,python,readline,Python,Readline,在Python中,您可以使用 f = open('file.txt','r') lines = f.readlines() 每一行都由\n分隔,但如果行的内容有\r则不会将其视为新行。我需要将所有\r转换为\n并获得正确的列表行 如果在行中执行.split('\r'),我将在列表中获得列表 我想打开一个文件,将所有\r替换为\n,关闭文件并再次读取,然后使用readlines(),但这似乎是浪费 我应该如何实现这一点 f = open('file.txt','rU') 这将使用Python打

在Python中,您可以使用

f = open('file.txt','r')
lines = f.readlines()
每一行都由
\n
分隔,但如果行的内容有
\r
则不会将其视为新行。我需要将所有
\r
转换为
\n
并获得正确的列表

如果在
行中执行
.split('\r')
,我将在列表中获得列表

我想打开一个文件,将所有
\r
替换为
\n
,关闭文件并再次读取,然后使用
readlines()
,但这似乎是浪费

我应该如何实现这一点

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

这将使用Python打开文件,并且
\r
被视为行尾。

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

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')

…尽管根据Python文档,此功能已被弃用,不应在新代码中使用。谢谢!这对我来说已经足够了。Tim,现在正确的方法是什么?在Python 3.x中,默认情况下,通用换行符支持处于启用状态,因此您无需执行任何操作。不幸的是,这对我不起作用,每次我在mac上调用readlines()时,我的列表长度始终为1!发现了问题。readlines()对我来说永远失败,但read()。split(“\r”)执行相同的功能并工作。此外,.split(“\n”)在每个文件上都会永久失败,原因可能与.readlines()不起作用的原因相同。我花了好几天才弄明白!这是我第一次在mac电脑上进行专业工作,不幸的是,我被绊倒了很长一段时间。这是OSX 10.9.1上的python 2.7.5。不幸的是,为“rU”打开文件并没有解决我的换行符/回车问题。实际上,如果您混合使用了
\n
\r
换行符,并且后者出现在由
\n
分隔的“实”行中,那么在我看来,在列表中获取列表是正确的。