Reputation: 466
I have a file that looks like this
25,6,73,5,3
3,4,5
0,6,3,78
53,68,9,3
how can it be read as integers and put into a list of lists( per row), without a fixed list size and number of lists?(meaning i can put as many numbers into one row and as many rows as i want)
Upvotes: 1
Views: 54
Reputation: 369064
Open the file, read line by line by iterating the open file object; split the line using str.split
, convert splited strings to int
:
>>> with open('/path/to/textfile.txt') as f:
... numbers = [map(int, line.strip().split(',')) for line in f]
...
>>> numbers
[[25, 6, 73, 5, 3], [3, 4, 5], [0, 6, 3, 78], [53, 68, 9, 3]]
Upvotes: 1
Reputation: 2646
Something like this should do the trick (not tested):
with open(fileName) as f:
content = f.readlines()
listOfLists = []
for line in content:
listOfLists.append(line.split(','))
Upvotes: 1