Python Forum

Full Version: seek method clarification
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,
I would like someone to clarify the seek method. I have this code (excuse formatting)

in_file = open('mydata4.txt','r+')
print(in_file.readline())
in_file.seek(0)
in_file.write('Hi!')
in_file.seek(0)
print(in_file.readline())
in_file.close()

which outputs

First Line
Hi!st Line

and I understand what is happening but when I do this

in_file = open('mydata4.txt','r+')
print(in_file.readline())
in_file.seek(0)
in_file.write('Hi!')
#in_file.seek(0) <-- comment out this line
print(in_file.readline())
in_file.close()

the output is

First LineHi!

and I just don't see why 'Hi!' doesn't overwrite the text after the first seek(0) and why is the second seek(0) even needed?

Thanks
Pete