我可以从打开读取的文件中获取文件修改时间吗(python)
像 file("foo.txt")
这样打开的文件是否有有关文件修改时间的信息?
基本上我想知道文件自某个时间以来是否已被修改或替换,但是如果在检查修改时间和打开文件之间替换了文件,那么您的信息不准确。
我怎样才能确定?
谢谢。
更新
@rubayeet:感谢您的回答(+1),我实际上没有想到这一点。但是……修改时间变了怎么办?也许我再次重新加载文件。但如果那个时间改变了怎么办?如果文件经常被触摸,我可能会永远陷入循环!我真正想要的是一种只获取打开文件句柄和修改时间的方法,而不存在潜在的无限循环。
PS您给出的答案实际上对于我的目的来说已经足够好了,因为该文件不会定期更改,这是我现在普遍感兴趣的。
更新2
通过思考之前的更新(并进行一些实验)我意识到,仅仅知道文件打开时的文件修改时间并没有多大用处,就像在阅读您的文件时修改了文件一样您读入的内容中可能包含部分或全部修改后的数据,因此您必须打开并读取/处理整个文件,然后再次检查 mtime (根据 @rubayeet 的答案)以查看是否有过时的数据。
Do files opened like file("foo.txt")
have any info about file modification time?
Basically I want to know if the file has been modified or replaced since a certain time, but if the file is replaced between checking modification time and opening the file, then you have inaccurate information.
How can I be sure?
Thanks.
UPDATE
@rubayeet: Thanks for the answer (+1), I actually didn't think of that. But... What to do if the modification time has changed? Perhaps I reload the file again. But what if it changes that time? If the file is being touched regularly I could end up in a loop forever! What I really want is a way to just get an open file handle and a modification time to go with it, without a potential infinite loop.
PS The answer you gave was actually plenty good enough for my purposes as the file won't be changed regularly, its general interest on my part now.
UPDATE 2
Thinking the previous update through (and experimenting a little) I realize that simply knowing the file modification time at the point the file was opened is not so much use as if the file is modified while reading you can have some or all of the modified data in the stuff you read in, so you'd have to open and read/process the whole file, then check mtime again (as per @rubayeet's answer) to see if you may have stale data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于简单的修改时间,您可以使用:
如果您想要回调功能之类的功能,您可以检查 python 的 inotify 绑定:pyinotify。
您本质上设置了一个监视管理器,如果受监视的目录中发生任何更改,它会在事件循环中通知您。您注册特定事件,例如打开文件(如果写入,则会更改修改时间)。
如果您对文件的独占访问感兴趣,我会指向 fnctl 模块,它在文件描述符上有一些低级的文件锁定机制。
For simple modtimes you would use:
If you want something like a callback functionality you could check the inotify bindings for python: pyinotify.
You essentialy set a watchmanager up, which notifies you in a event-loop if any changes happens in the monitored directory. You register for specific events, like opening a file (which changes the modtime if written to).
If you are interested in an exclusive access to a file, i would point to the fnctl module, which has some lowlevel and file-locking mechanism on filedescriptors.