0

I have a number of text files with a layout like below,

heading
subheading
info1
info2
info3

where the character count of each line will vary from file to file. For each file, I'd like to store line 2 as a Python variable.

I can load the whole file into a variable,

with open('data.txt', 'r') as myfile:
    data=myfile.read().replace('\n', '')

but I am unsure how to specify to read only line 2.

birac
  • 568
  • 1
  • 8
  • 18

2 Answers2

2

You don't need to read the entire file, just the lines before the one you want. The simplest way to do this is with the itertools module.

with open('data.txt', 'r') as myfile:
    data = next(itertools.islice(myfile, 1, None))

The slice produces elements 1 though the end of the iterable myfile (with element 0 being the first line). next simply produces the next available item from that iterable, giving you line 2.

(I was unaware of the linecache module in the duplicates; that's a better solution for the immediate problem.)

chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can read one line at a time with the readline function:

with open('data.txt', 'r') as myfile:
    line1=myfile.readline()
    data=myfile.readline().replace('\n', '')

For some arbitrary line you can iterate through the file until you get to that line:

with open('data.txt', 'r') as myfile:
    dataline = 4 # any number less than or equal to the number of lines in the file
    for line in range(dataline - 1):
        myfile.readline()
    data=myfile.readline().replace('\n', '')
C. Braun
  • 5,061
  • 19
  • 47