在python中打开后检查打开的文件是否已被删除 [英] Check if an open file has been deleted after open in python

查看:77
本文介绍了在python中打开后检查打开的文件是否已被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检查文件是否已在python中删除或重新创建?

Is it possible to check if a file has been deleted or recreated in python?

例如,如果您在脚本中执行了 open("file"),然后在该文件仍处于打开状态时,您将执行 rm文件;触摸文件; ,那么脚本将仍然保留对旧文件的引用,即使该文件已被删除.

For example, if you did a open("file") in the script, and then while that file is still open, you do rm file; touch file;, then the script will still hold a reference to the old file even though it's already been deleted.

推荐答案

是.使用 os.stat()函数检查文件长度.如果长度为零(或函数返回错误找不到文件"),则有人删除了文件.

Yes. Use the os.stat() function to check the file length. If the length is zero (or the function returns the error "File not found"), then someone deleted the file.

或者,每次需要向文件中写入内容时,都可以打开+写入+关闭文件.缺点是打开文件的速度很慢,因此如果您需要写入大量数据,这是不可能的.

Alternatively, you can open+write+close the file each time you need to write something into it. The drawback is that opening a file is a pretty slow operation, so this is out of the question if you need to write a lot of data.

为什么?因为新文件不是您一直处于打开状态的文件.简而言之,Unix文件系统具有两个级别.第一个是目录条目(即文件名,文件大小,修改时间,数据指针),第二个是文件数据.

Why? Because the new file isn't the file that you're holding open. In a nutshell, Unix filesystems have two levels. One is the directory entry (i.e. the file name, file size, modification time, pointer to the data) and the second level is the file data.

打开文件时,Unix使用该名称查找文件数据.之后,它仅在第二级上运行-对目录条目的更改对任何打开的文件句柄"均无效.这就是为什么您可以删除目录条目的原因:您的程序未使用它.

When you open a file, Unix uses the name to find the file data. After that, it operates only on the second level - changes to the directory entry have no effect on any open "file handles". Which is exactly why you can delete the directory entry: Your program isn't using it.

使用 os.stat()时,您不会查看文件数据,而是再次查看目录条目.

When you use os.stat(), you don't look at the file data but at the directory entry again.

从正面看,这使您可以创建只有您的程序才能看到的文件:打开文件,将其删除然后使用.由于该文件没有目录条目,因此没有其他程序可以访问数据.

On the positive side, this allows you to create files which no one can see but your program: Open the file, delete it and then use it. Since there is no directory entry for the file, no other program can access the data.

从消极的一面看,您无法轻松解决诸如此类的问题.

On the negative side, you can't easily solve problems like the one you have.

这篇关于在python中打开后检查打开的文件是否已被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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