Ad

How Do I Compile A List From One Line In Python?

- 1 answer

I want to create a list from one line in a file, but I cannot find a way on how to do it, does anybody have any tips on how to do it?

"text.txt file"
22 21 20

And this is my latest attempt to do it, but the list is not split into three elements, but instead is one whole string.

f = open("file.txt")

line = f.readline()
line = line.replace(" ", ", ")
list1 = [line]
print(list1)

Output:
['22, 21, 20']
Ad

Answer

Use split() to split the string into a list of strings. If you want to turn those strings into ints, call int on each one.

with open("file.txt") as f:
    list1 = f.readline().split()

print(list1)              # ['22', '21', '20']
print([int(n) for n in list1])  # [22, 21, 20]
Ad
source: stackoverflow.com
Ad