Readline() anomaly

I am currently doing LP3THW ex.16 and I stumbled upon something interesting. What I learnt is that when you open an existing file in ‘w’ mode, it’s contents are erased. Below is the code with which I was experimenting.

from sys import argv

script, filename = argv

file1 = open(filename)
print(f"First line in file1:\n{file1.readline()}")
file2 = open(filename)
file3 = open(filename, 'w')
print(f"Remaining content of file 1:\n{}")
print(f"Full content of file2:\n{}")

The file that I passed is this -
Hey!! this is an awesome file!!
So awesome that it doesn’t contain anything
Except these 2 lines

The output for this script is:

My doubt is, after I open a file in ‘w’ mode all it’s contents must be erased. Then why is print on line 9 printing the remaining file whereas the print on line 10 isn’t printing anything. I read the python documentation, searched for 2 hours on the internet but couldn’t figure out exactly what is going on. I guess that when I do a readline() on a file object, all it’s contents are kind of buffered. Correct me if I am wrong…
Thanks in advance :slight_smile:

Hi @vineeth under the following link you’ll find a good list of all python open()-modes.

Then you open a file with “w” the content will be erased. In your case you store the file first in the variable “file1” for reading only (default) and then open it again in the variable "file2 "(also for reading only) and then again in the variable “variable3” for writing only. So I assume Python will cache the content of variable “file1” and “file2” so you get some output then you print the variable “file2” even if you erased later in the code the real file on the harddrive with the open-operation in variable “file3”.

Thanks for the reply @DidierCH. So, basically it is caching the file once I perform a readline() on it. Got it :+1:
Thanks a lot! :smile:

thanks for bringing this up, I encountered the same symptoms thought I made a coding mistake and moved on, having now read the docs which clearly say ‘w’ mode will result in ‘an existing file with the same name will be erased’ (I really need to form the habit of reading the docs again, but we’re always in a rush)

looks like mode ‘r+’ will stop the contents being overwritten
cheers for the lesson

Welcome to the unix legacy of Python. If you don’t want it to be erased then you can do a+ instead (I believe. You’ll have to check that in the docs to be sure).