Mikhail Geyer Mikhail Geyer - 1 year ago 70
Linux Question

How python reads a file when it was deleted after being open

I have difficalties to understand the concept of how python reads a file when it was deleted after being

. Here is the code

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

Text and binary modes give the same result.

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

From where python gets the data if an open file does not exist anymore?

I run this test on

  • python 3.4.3 / 3.5.2

  • ubuntu 14.04 / 16.04

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download