Reputation: 4330
This is simple but I just cant seem to get it right.
I have a text file containing numbers in the form
0 1 2
3 43
5 6 7 8
and such.
I want to read these numbers and store it in a list such that each number is an element of a list. If i read the entire file as a string, how can I split the string to get these elements separated?
Thanks.
Upvotes: 1
Views: 158
Reputation: 14313
First, open the file. Then iterate over the file object to get each of its lines and call split() on the the line to get a list of strings. Then convert each string in the list to a number:
f = open("somefile.txt")
nums = []
strs = []
for line in f:
strs = line.split() #get an array of whitespace-separated substrings
for num in strs:
try:
nums.append(int(num)) #convert each substring to a number and append
except ValueError: #the string cannot be parsed to a number
pass
nums now contains all of the numbers in the file.
Upvotes: 1
Reputation: 298046
You can iterate over the file object as if it were a list of lines:
with open('file.txt', 'r') as handle:
numbers = [map(int, line.split()) for line in handle]
A slightly simpler example:
with open('file.txt', 'r') as handle:
for line in handle:
print line
Upvotes: 3