Ram Idavalapati
Ram Idavalapati

Reputation: 714

What happens exactly when a file is opened in read mode in python

But What I know is when we create file object, the file won't load into RAM. Then if I delete it from hard disk, then from where I am accessing the file content?

Upvotes: 1

Views: 1688

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9664

The details might depend on the OS you're using, but for Linux you're talking about, the more appropriate question on how is this possible would not be how did the file get opened, but what happens when the file is being deleted. Answer to which you can find in the description of unlink(2) syscall:

...
   unlink() deletes a name from the filesystem.  If that name was the last
   link to a file and no processes have the file open, the file is deleted
   and the space it was using is made available for reuse.

   If  the  name  was the last link to a file but any processes still have
   the file open, the file will remain in existence until  the  last  file
   descriptor referring to it is closed.
...

If you look at it from the the python perspective, the file may no longer have a name in the file system, but it's still there and you can also do the following:

>>> f = open('TEST')
>>> os.unlink('TEST')
>>> print(os.fstat(f.fileno()))
os.stat_result(st_mode=33188, st_ino=146934248, st_dev=2431, st_nlink=0, st_uid=1000, st_gid=100, st_size=5, st_atime=1517409090, st_mtime=1517409090, st_ctime=1517409124)

Upvotes: 1

Related Questions