-3

Say, I have a file which has the following content:

1
2
3
4
5
6
7
8
9
10

I want create it into a list of integers in Python3, i.e [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

f = open("stan.txt","r")

myList = []

for line in f:
   myList.append(line)

print(myList)

lst = []
for i in myList:
    i = i[:-1]
    lst.append(int(i))
print(lst)

It is my verbose code. Is there an elegant and concise way to do it?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Fadai Mammadov
  • 55
  • 2
  • 2
  • 9

2 Answers2

1

If the file is not very large, read it as a string, split the string into numbers, and apply int() to each of them using list comprehension:

with open("stan.txt") as f:
    lst = [int(x) for x in f.read().split()]
DYZ
  • 55,249
  • 10
  • 64
  • 93
-1

Use a list comprehension:

with open('stan.txt') as f:
  my_list = [ int(i) for i in f ]
rumdrums
  • 1,322
  • 2
  • 11
  • 25