0

Is there a way to "un-readline" a line of text from a file opened with open()?

#!/bin/env python

fp = open("temp.txt", "r")

# Read a line
linein = fp.readline()
print(linein)

# What I am looking for comes here
linein = fp.unreadline()

# Read the same line
linein = fp.readline()
print(linein)

The input file temp.txt:

FIRST_LINE
SECOND_LINE

Expected output:

FIRST_LINE
FIRST_LINE
ysap
  • 7,723
  • 7
  • 59
  • 122

1 Answers1

3

Not automatically, but you can first remember where in the file the line began using fp.tell, and then usefp.seek to reset the file pointer to the same point.

#!/bin/env python

with open("temp.txt", "r") as fp:
    # Read a line
    start_of_line = fp.tell()
    linein = fp.readline()
    print(linein)

    fp.seek(start_of_line)

    # Read the same line
    linein = fp.readline()
    print(linein)
chepner
  • 497,756
  • 71
  • 530
  • 681