Reputation: 13
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
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
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
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