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! :) ) Commented 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 Commented 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?) Commented 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"? Commented 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)
Sign up to request clarification or add additional context in comments.

10 Comments

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.
i think the problem is at i += 1?
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.
you changed the i to = 1 and you moved the print
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)?
|
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 Comments

Nah this is not a homework question, i am trying to make a little calculator for my website :P
would changing i += 1 to i += (which) help?
0

You can simply do this:

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

Now you can guess the rest of it.

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.