I have a text file that 10 numbers 0 to 10 written line by line(downward).
Such as;
2
4
5
1
7
6
9
0
2
4
So, how can I write those numbers in a list while reading?
sample of my code:
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()
After pushing numbers in list:
emptyList=[2,4,5,1,7,6,9,0,2,4]
print(emptyList)
I'm trying to get result like that:
[2,4,5,1,7,6,9,0,2,4]
You can use the list.append()
method after you convert each line to an integer:
emptyList = []
while line:
print(line)
emptyList.append(int(line))
line = read.readline()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.