Python在打开文件后如何读取文件 [英] How Python reads a file when it was deleted after being opened

查看:102
本文介绍了Python在打开文件后如何读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

open 'ed被删除后,我很难理解Python读取文件的概念。这里是代码:

 >>> import os 
>>> os.system('猫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:没有这样的文件或目录
256
>>> f.read()
'Hello world!\\\
'
>>>

文本和二进制模式给出相同的结果。

我也试过这个大于1Gb大小的文件,在被删除后也被读取。即使对于非常大的文件,打开的操作几乎是瞬间发生的。



如果打开的文件不存在,Python从哪里获取数据?



on


  • python 3.4.3 / 3.5.2

  • ubuntu 14.04 / 16.04


解决方案<与Python无关。在C,Fortran或Visual Cobol中,只要代码从打开系统调用获取句柄,就会具有相同的行为。

在Linux / Unix系统上,一旦进程有文件句柄,即使文件被删除,文件也可以读取。有关更多详细信息,请查看(我不知道是否可以这样做,它似乎是)

在Windows上,你只是不会'只要被进程锁定,就能够删除文件。


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

解决方案

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.

这篇关于Python在打开文件后如何读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆