Skip to main content
 首页 » 编程设计

python之在 python 中以读取模式打开文件时到底发生了什么

2025年01月19日8bhlsheji

  • 我有一个文件test.txt
  • 我在 python 中以读取模式打开它 fp = open('test.txt', 'r')
  • 现在我从硬盘上删除了那个文件($ rm test.txt)
  • 现在如果我说 fp.read() 我将从文件中获取所有内容

但据我所知,当我们创建文件对象时,该文件不会加载到 RAM 中。那么如果我从硬盘上删除它,那么我从哪里访问文件内容?

请您参考如下方法:

详细信息可能取决于您使用的操作系统,但对于您正在谈论的 Linux,关于这如何可能的更合适的问题不是文件是如何打开的,而是文件打开时会发生什么被删除。您可以在 unlink(2) 系统调用的描述中找到答案:

... 
   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. 
... 

如果从 python 的角度来看,文件可能在文件系统中不再有名称,但它仍然存在,您还可以执行以下操作:

>>> 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)