使用 readlines 导入后从 Python 列表中删除 \r\n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24946640/
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-08-19 05:30:27  来源:igfitidea点击:

Removing \r\n from a Python list after importing with readlines

pythonreadlines

提问by Justin

I have saved a list of ticker symbols into a text file as follows:

我已将股票代码列表保存到文本文件中,如下所示:

MMM
ABT
ABBV
ANF
....

Then I use readlines to put the symbols into a Python list:

然后我使用 readlines 将符号放入 Python 列表中:

stocks = open(textfile).readlines()

However, when I look at the list in it contains Windows end-of-line delimiter which I do not want:

但是,当我查看其中的列表时,它包含我不想要的 Windows 行尾分隔符:

list: ['MMM\r\n', 'ABT\r\n', 'ABBV\r\n', 'ANF\r\n', 'ACE\r\n', 'ACN\r\n', 'ACT\r\n', 'ADBE\r\n', 'ADT\r\n', 'AMD\r\n', 'AES\r\n', .....

Can someone suggest the easiest way to remove these unwanted characters?

有人可以建议删除这些不需要的字符的最简单方法吗?

回答by TheSoundDefense

You could replace \r\nwith the empty string in a replacecommand.

您可以用命令中\r\n的空字符串替换replace

stocks = [x.replace("\r\n","") for x in stocks]

回答by ssm

readlines()should never be used unless you know that the file is really small. For your application, it is better to use rstrip()

readlines()除非您知道文件非常小,否则不应使用。对于您的应用程序,最好使用rstrip()

with open(filename, 'r') as f:
    for l in f:
        l = l.rstrip()
        # other operations. 

回答by roippi

That's basically how readlinesworks. You could post-process it:

这基本上是如何readlines工作的。您可以对其进行后处理:

stocks = [x.rstrip() for x in stocks]

But I prefer not using readlinesat all if I don't want EOL character(s), instead doing:

readlines如果我不想要 EOL 字符,我宁愿不使用,而是这样做:

stocks = open(textfile).read().splitlines()

Or even better:

或者甚至更好:

with open(textfile) as f:
    stocks = f.read().splitlines()

(it almost certainly won't make a difference here, but using context managers to explicitly close file objects is a good habit to get into)

(在这里几乎可以肯定不会有什么不同,但使用上下文管理器显式关闭文件对象是一个好习惯)

回答by martineau

You could do it like this:

你可以这样做:

stocks = open(textfile).read().splitlines()