-1

I have got a .txt file that contains a lot of lines. I would like my program to ask me what line I would like to print and then print it into the python shell. The .txt file is called packages.txt.

animuson
  • 53,861
  • 28
  • 137
  • 147
EatMyApples
  • 465
  • 6
  • 11
  • 18

3 Answers3

8

If you don't want to read in the entire file upfront, you could simply iterate until you find the line number:

with open('packages.txt') as f:
    for i, line in enumerate(f, 1):
        if i == num:
            break
print line

Or you could use itertools.islice() to slice out the desired line (this is slightly hacky)

with open('packages.txt') as f:
    for line in itertools.islice(f, num+1, num+2):
        print line
spinlok
  • 3,561
  • 18
  • 27
4

If the file is big, using readlines is probably not a great idea, it might be better to read them one by one until you get there.

line_number = int(raw_input('Enter the line number: '))
with open('packages.txt') as f:
    i = 1
    for line in f:
        if i == line_number:
            break
        i += 1
    # line now holds the line 
    # (or is empty if the file is smaller than that number)
    print line

(Updated to fix the mistake in the code)

Marga Manterola
  • 642
  • 1
  • 4
  • 12
0

How to refer to a specific line of a file using line number ? as in java if line number = i and file is stored in f then f(i) would do.

Roy
  • 33
  • 6