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

5
  • 1
  • @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 :) Commented Apr 30, 2016 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. Commented Apr 30, 2016 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 :) Commented Apr 30, 2016 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! Commented Apr 30, 2016 at 20:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.