How to "un-readline()" a line from a file?
Question:
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
Answers:
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)
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
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)