0

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!


*Like sstream in

dimo414
  • 47,227
  • 18
  • 148
  • 244
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    Related [Skip first couple of lines while reading lines in Python file](http://stackoverflow.com/q/9578580) and [How can I write a csv file with multiple header lines with pandas to\_csv()?](http://stackoverflow.com/q/22356746) – Bhargav Rao Apr 30 '16 at 19:47
  • @BhargavRao, I can't use Pandas :/ The first link is nice, but I want to read the first three lines, not just skip them! Thanks though :) – gsamaras Apr 30 '16 at 19:50
  • Did you read the other answers in the first link? As you are using readlines, a couple of the answers are valid and helpful if you try to use the slice syntax there. Alternatively the `enumerate` answer is also helpful there. – Bhargav Rao Apr 30 '16 at 19:52
  • @BhargavRao, I am currently doing so, yeap the `enumerate` should come in handy. I will update my question with a better attempt, if any. As for readlines, it's a not a must, so if there is another way, bring it on..people :) – gsamaras Apr 30 '16 at 19:54
  • @BhargavRao thank you very much for the links. I could narrow down the question now, *discarding the part that your suggestion solved*! – gsamaras Apr 30 '16 at 20:03

1 Answers1

1

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.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44