Super Roy
Super Roy

Reputation: 13

How can I get python to read each line in a txt file and make seperate lists?

Say I have a .txt file with some integers.

#txt file called ints.txt

1,3
4
5,6

How can I get python to read each line and make them into separate lists?

The output I'm looking for:

['1','3']
['4']
['5','6']

I tried this code but it only prints the first element of the txt file as a list. I want it to print the subsequent elements too.

x = open("ints.txt", "r")
x = x.readline()
x = x.strip()
x = x.split(" ")


for i in x:

    print(x)

Output:
['1','3']
['1','3']

Appreciate the help, my friends :)

Upvotes: 0

Views: 105

Answers (3)

Nj Nafir
Nj Nafir

Reputation: 568

This will help you

`with open("test.txt", "r") as openfile:
    for line in openfile:
        new_list = [x for x in line.split(" ")]
        print(new_list)

Upvotes: 0

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

Try this:

with open('file/path') as f:
    lines = [i.strip().split(',') for i in f.readlines() if i.strip()]

To print the list of lists in each line, do this :

print(*lines, sep='\n')

Upvotes: 1

Raymond Reddington
Raymond Reddington

Reputation: 1837

Try readlines method. Something like that.

with open("ints.txt", "r") as f:
    for line in f.readlines():
        items = line.split(',')

Upvotes: 0

Related Questions