1

I have got this code so far. You input a number and it should read the specific line in the packages.txt file and print it into the python shell.In the code below, if you enter "3" in for example it will print line 1-3 which i do not want it to do.

which = input('Which package would you like?: ')

    with open('packages.txt') as f:
        i = 0
        for line in f:
            if i == (int(which)):
                break
            i += 1
            print (line)
4
  • 2
    Can you explain why it prints lines 1-3? (If you can, then you are a good way to solving the problem! :) )
    – huon
    May 6, 2012 at 5:29
  • I think that python maybe reads line 0 to (which) and prints them? or am i wrong here? :P May 6, 2012 at 5:32
  • Yes, that is what happens, but why does that happen? (Which part of the code means that every line up to which is printed? Where does Python iterate through the lines and where does the print statement occur?)
    – huon
    May 6, 2012 at 5:36
  • well, you input a number, i gets set to that number and it will print until f is set to 0? i think that the problem occurs in "i += 1"? May 6, 2012 at 5:39

3 Answers 3

2

Think about the flow of the code and when print (line) is being called.

Can you see the 2 very important differences between this code and yours?

which = input('Which package would you like?: ')

with open('packages.txt') as f:
    i = 1
    for line in f:
        if i == (int(which)):
            break
        i += 1
print (line)
10
  • f doesn't change at all, it's the file. i is changing, that's what the line i += 1 does, it adds 1 to the value of i.
    – jgritty
    May 6, 2012 at 5:38
  • i think the problem is at i += 1? May 6, 2012 at 5:41
  • Nope, that line is fine, we are reading through the file f one line at a time. i is keeping track of which line we are on.
    – jgritty
    May 6, 2012 at 5:42
  • you changed the i to = 1 and you moved the print May 6, 2012 at 5:45
  • oh i get it now, i is the line it is reading, so when the program starts running it will start by reading line 1? and then set it to the (which)? May 6, 2012 at 5:46
1

You can enumerate over f to get the index of a line and print it if it matches which. I assumed this is a homework question, so not putting complete code here :)

2
  • Nah this is not a homework question, i am trying to make a little calculator for my website :P May 6, 2012 at 5:35
  • would changing i += 1 to i += (which) help? May 6, 2012 at 5:40
0

You can simply do this:

lines = open('packages.txt').readlines()

Now you can guess the rest of it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.