Reputation: 475
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
Reputation: 5791
You can simply do this:
lines = open('packages.txt').readlines()
Now you can guess the rest of it.
Upvotes: 0
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
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