'Read line of numbers into lists in Python

I am trying to read two lines from a file into two lists such that each line is in one list.

data.txt:

1,5,7,18,9,8,12
2,41,12,11,1,10

The code I've tried:

list1 = []
list2 = []
infile = open("data.txt","r")
line = infile.readline()
for line in infile:
    line = line.split(',')
    list1.append(float(line))
    line = infile.readline()
    list2.append(float(line))
    print(list1)
    print(list2)
print()

What I want to have:

list1 = [1, 5, 7, 18, 9, 8, 12]
list2 = [2, 41, 12, 11, 1, 10]

How can I fix my code?



Solution 1:[1]

There are many things that are wrong in your code, so I'll just post a better way:

with open('data.txt', 'r') as file:
    list1 = [int(number) for number in file.readline().split(',')]
    list2 = [int(number) for number in file.readline().split(',')]

print(list1)
print(list2)

Output:

[1, 5, 7, 18, 9, 8, 12]
[2, 41, 12, 11, 1, 10]

You can also do it in one line:

list1, list2 = [[int(n) for n in line.split(',')] for line in open('data.txt').readlines()]

Solution 2:[2]

list1=[]
list2=[]
f = open("inputfile.txt","r")
lines = f.readlines()
f.close()
list1 = [int(x) for x in lines[0].split(",")]
list2 = [int(x) for x in lines[1].split(",")]

print(list1)
print(list2)

output:

[1, 5, 7, 18, 9, 8, 12]
[2, 41, 12, 11, 1, 10]

Solution 3:[3]

list1=[]
list2=[]
lines = []
infile = open("data.txt","r")
for line in infile :
    line = line.split(',')
    lines.append(line)
list1 = lines[0]
list2 = lines[1]

print (list1)
print (list2)

Solution 4:[4]

Reading the file line by line is fine - you can leverage map to convert the numbers and add them into a list of lists of numbers. You may want to open files with a contexthandler to close them gracefuly in case of exceptions.

Create demo file:

with open("numbers.txt","w") as nums:
    nums.write("""2, 7, 9, 3, 5, 7
1, 2, 3, 4, 5, 6""")

then read it in again

numbers = []
with open("numbers.txt") as nums:   
    for line in nums:
        line = line.strip() # remove newline at end and other whitespace
        if line: # avoid empty lines
            n = list(map(int, line.split(", ")))
            numbers.append(n)
       
row1, row2 = numbers 
print(row1)
print(row2)

Output:

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

Now you have two lists of numbers and can work with them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mahesh Karia
Solution 3 rahul mehra
Solution 4 Patrick Artner