Home > database >  How do I compile a list from one line in python?
How do I compile a list from one line in python?

Time:03-24

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']

CodePudding user response:

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]

CodePudding user response:

you can use this:

with open("tasks.txt", 'r') as data:
    data=[int(each_int) for ele  in data.readlines() for each_int in ele.split() ]

print(data)

  • Related