EatMyApples
EatMyApples

Reputation: 475

Print specific line in python?

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)

Upvotes: 1

Views: 5662

Answers (3)

nkh
nkh

Reputation: 5791

You can simply do this:

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

Now you can guess the rest of it.

Upvotes: 0

jgritty
jgritty

Reputation: 11915

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)

Upvotes: 2

ACC
ACC

Reputation: 2560

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 :)

Upvotes: 1

Related Questions