-2

Regardless of how basic this task seems to be I am struggling to read a specific line of a file in Python.

I am creating a quotation system for reading and writing files is a key part. In the code the line which needs to get read needs to correspond to a place value predefined by the variable Position. I then want the line to be stored to a variable.

I am trying to look for an efficient way where you don't have to go through the whole file. I have tried using file.readline(Position) but that keeps displaying 0. I have included parts of my code for context.

value = self.option.get()
Position= int(array.index(value))
print(value) #test
print(Position) #test

file= open("Height_File.txt", "r")
Height= file.readline(Position)
print(Height)#test
file.close() 
timgeb
  • 76,762
  • 20
  • 123
  • 145
V.Bon
  • 71
  • 1
  • 1
  • 11

3 Answers3

3

If you want a specific line from a file you can use the linecache module's linecache.getline function.

Demo:

Suppose your file is named testfile.txt and has the content

line1
line2
line3

Then you would access line2 with

>>> import linecache
>>> linecache.getline('testfile.txt', 2)
'line2\n'
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

I'm sure there's an even better way, but off the top of my head, this will use an iterator, so it will be more efficient than above for just reading one line.

def read_line(path, line_number, encoding=None):
    with open(path, 'r', encoding=encoding) as f:
        for index, line in enumerate(f):
            if index == line_number:
                yield line.strip('\r\n')

Note, to call, you would do: next(read_line(path, line_number))

-1

Use it like this.

Height = file.readlines()[position]

This gives you the line with the position you enter(starting from 0)

Rockybilly
  • 2,938
  • 1
  • 13
  • 38