如何在python中读取文本文件的列表中推送数字

2024-09-28 01:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,10个数字0到10写一行(向下)

例如:

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

在列表中输入数字后:

emptyList=[2,4,5,1,7,6,9,0,2,4]
print(emptyList)

我试图得到这样的结果:

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


Tags: thetotxt列表readreadlineisuse

热门问题