gsamaras - 1 year ago 103

Python Question

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

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.