How Python reads a file when it was deleted after opening

I'm having difficulty understanding the concept of how Python reads a file when it was deleted after 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 large files larger than 1 GB, and they were also read after deletion. The open operation occurs almost instantly even for very large files.

Where does Python get data if the open file no longer exists?

I tested this test for

  • python 3.4.3 / 3.5.2
  • ubuntu 14.04 / 16.04
+6
source share
2 answers

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

On Linux / Unix systems, when a process has a file descriptor, it can read it even if the file is deleted. Check this question for more details (I was not sure if this was normal, it looks like)

On Windows, you simply cannot delete the file until it is locked by the process.

+6
source

Linux separates the directory structure and the files themselves. The file is identified by inode. Therefore, when you open a file by name, you read the directory structure, find the index corresponding to the name, and then open the inode file. Deleting a file or renaming it will change the directory structure, but will not affect the inode. The file itself will only be deleted when it is closed, so links to the index will not be left (both in the directory structure and in running processes).

+3
source

Source: https://habr.com/ru/post/1011499/


All Articles