0

我是 Python 新手,我有一个.txt包含数字的文件,我使用以下代码将它们读入 Python 中的数组:

numberInput = []
with open('input.txt') as file:
     numberInput = file.readlines()
print numberInput

不幸的是,输出如下所示:

['54044\r\n', '14108\r\n', '79294\r\n', '29649\r\n', '25260\r\n', '60660\r\n', '2995\r\n', '53777\r\n', '49689\r\n', '9083\r\n', '16122\r\n', '90436\r\n', '4615\r\n', '40660\r\n', '25675\r\n', '58943\r\n', '92904\r\n', '9900\r\n', '95588\r\n', '46120']

如何裁剪\r\n附加到数组中每个数字的字符?

4

2 回答 2

2

您在字符串末尾看到的\r\n是换行符(回车符后跟换行符)。您可以使用以下方法轻松删除它str.strip

numberInput = [line.strip() for line in file]

这是一个列表推导,它遍历您的文件(一次一行)并去除在该行任一端找到的任何空白。

但是,如果您想将文件中的数字用作整数,则实际上可以避免剥离行,因为int构造函数将忽略任何空格。如果您直接进行转换,它的外观如下:

numberInput = [int(line) for line in file]
于 2013-07-02T00:38:28.700 回答
1

您应该使用str.splitlines()而不是readlines()

numberInput = []
with open('input.txt') as file:
     numberInput = file.read().splitlines()
print numberInput

这将读取整个文件并通过“通用换行符”将其拆分,因此您可以获得相同的列表,而无需\r\n.

看到这个问题: Best method for reading newline delimited files in Python and discard the newlines?

于 2013-07-02T01:00:12.220 回答