Reputation: 97
I am using this code to read a text file into a list.
with open("products.txt", "r") as f:
test=f.read().splitlines()
print(test)
The resulting output is:
['88888888,apple,0.50', '99999999,pear,0.20', '90673412,orange,1.20']
I need the output to look like below so I can reference the individual elements.
['88888888', 'apple', '0.50', '99999999', 'pear', '0.20', '90673412', 'orange', '1.20']
Upvotes: 4
Views: 7334
Reputation: 107347
You can use a nested list comprehension :
with open("products.txt", "r") as f:
test=[i for line in f for i in line.split(',')]
Or use csv
module to refuse of splitting the lines :
>>> import csv
>>> with open('products.txt') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=',')
test=[i for row in spamreader for i in row]
Upvotes: 2