Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Python reads a file when it was deleted after being opened

I'm having difficulties in understanding the concept of how Python reads a file when it was deleted after being open'ed. Here is the code:

>>> import os
>>> os.system('cat foo.txt')
Hello world!
0
>>> f
<_io.TextIOWrapper name='foo.txt' mode='r' encoding='UTF-8'>
>>> os.system('rm -f foo.txt')
0
>>> os.system('cat foo.txt')
cat: foo.txt: No such file or directory
256
>>> f.read()
'Hello world!\n'
>>>

Text and binary modes give the same result.

I tried this also for big files with more than 1Gb size and they were also read after being deleted. The operation of open happens almost instantaneously even for very big files.

From where does Python get the data if an open file does not exist anymore?

I ran this test on

  • python 3.4.3 / 3.5.2
  • ubuntu 14.04 / 16.04
like image 913
Mikhail Geyer Avatar asked Oct 20 '16 07:10

Mikhail Geyer


People also ask

How do you delete a file which is open in Python?

In Python, you can use the os. remove() method to remove files, and the os. rmdir() method to delete an empty folder. If you want to delete a folder with all of its files, you can use the shutil.

How do you delete a file after reading Python?

Using the os module in python To use the os module to delete a file, we import it, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter. You can not just delete a file but also a directory using the os module.

Why does LSOF show deleted files?

lsof is used to list all the deleted files which are still on disk due to open file descriptors. Memory is not immediately freed because the running process still has an open file handle to the just-deleted file.


1 Answers

Nothing to do with Python. In C, Fortran, or Visual Cobol you'd have the same behaviour as long as the code gets its handle from open system call.

On Linux/Unix systems, once a process has a handle on a file, it can read it, even if the file is deleted. For more details check that question (I wasn't sure if it was OK to do that, it seems to be)

On Windows you just wouldn't be able to delete the file as long as it's locked by a process.

like image 130
Jean-François Fabre Avatar answered Sep 28 '22 10:09

Jean-François Fabre