-1

How can I take text file and access/return a specific line from the file? For example, "File.txt" is 100 lines long and I want the information that's contained on lines 1,31,61 and 91.

dataFile = open("File.text","a+")
jake
  • 3
  • 1

1 Answers1

1

Do you want something like this?

def get_lines(filename, line_numbers):
    with open(filename) as f:
        for line_number, line in enumerate(f):
            if line_number in line_numbers:
                yield line_number, line


for line_number, line in get_lines('tmp.txt', (1, 3)):
    print(line_number, line)

This code returns a generator iterator so you should loop through it.

Ben
  • 5,952
  • 4
  • 33
  • 44