我如何将数字推入可在python中读取文本文件的列表中

时间:2018-08-25 23:28:04

标签: python python-3.x

我有一个文本文件,其中10个数字0到10逐行(向下)写入。

例如;

"details"

那么,如何在阅读时将这些数字写在列表中?

我的代码示例:

2
4
5
1
7
6
9
0
2
4

在列表中输入数字后:

emptyList=[] # I need to push into "testnumbers.txt"
read = open('testnumbers.txt')
# use readline() to read the first line 
line = read.readline()
# use the read line to read further.
# If the file is not empty keep reading one lineat a time, till the file is empty
while line:
    # print line
    print(line)
    line = read.readline()
read.close()

我正试图获得这样的结果:

  

[2,4,5,1,7,6,9,0,2,4]

1 个答案:

答案 0 :(得分:-2)

将每行转换为整数后,可以使用list.append()方法:

emptyList = []
while line:
    print(line)
    emptyList.append(int(line))
    line = read.readline()