gsamaras gsamaras - 2 years ago 136
Python Question

Parsing multiple values from a file in Python

The file is like this:

1 118 1
1 285 3
39861 27196 5

So, I would like to parse the file by storing the numbers in variables, since I know apriori that every line contains three integers*, how should I do it?

Here is my attempt:

f = open(fname, 'r')
no_of_headers = 3
for i, line in enumerate(f, no_of_headers):
print line

Here instead of reading into line, it should be modified to read to a, b and c, since we know that every line has three numbers!


Answer Source

Just use Python's (limited) pattern recognition syntax:

for i, line in enumerate(f, no_of_headers):
    a,b,c = line.strip().split() # splits the line by whitespace

This assigns each element of the split line to a, b, c respectively. Since each line contains exactly three elements, a is mapped to the first element, b to the second, and c to the third.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download