0

I created an empty file as follows:

touch foo.txt

Then, I opened up a Python interactive session, and typed the following:

>>> f = open("foo.txt", "w")
>>> print("Hello", file=f)

At this point, in another terminal, I typed the following:

rm foo.txt

Now, back in the Python interactive session, I typed:

>>> print("World", file=f)

This did not give an error. Why not? The file at this point has been deleted. So how is it still working?

Then, I tried the following in the same Python interactive session:

>>> f.close()
>>> f = open("foo.txt")

Now, the second of the above two statements gave an error, saying "No such file or directory 'foo.txt'". Why is it giving an error now? If the file still existed even after the rm command, why is trying to open the file failing?

Programmer
  • 369
  • 1
  • 10
  • On Unix, files and filenames (aka links) are like Python objects and references. Using `rm` just unlinks a name, as if reassigning/removing a reference in Python. This does not delete the object/file. The actual object/file will be removed later by a GC when all references are gone. – that other guy Dec 14 '18 at 18:35

1 Answers1

1

When you open a file, it gets loaded in the open file table this tables exists in the computer memory (RAM), after that all modifications made to that file are only saved to the same file loaded in that table and not the one on the disk, even if you delete your file from the disk it still exists in the open file table. Hope this make the picture a little bit clearer.

Reda Meskali
  • 275
  • 3
  • 9