获取文本文件何时被另一个程序编辑 [英] Getting when a text file is edited by another program

查看:51
本文介绍了获取文本文件何时被另一个程序编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 python 脚本(我们称之为 file_1.py),它用新内容覆盖文本文件的内容,它工作得很好.我有另一个 python 脚本 (file_2.py),它读取文件并对文件中的数据执行操作.使用 file_2.py 我一直在尝试获取文本文件何时由 file_1.py 编辑,然后在添加新数据后立即对其进行处理.我查看了 subprocess module 但我真的不知道如何在不同的文件中使用它.到目前为止,这是我所拥有的:

file_1.py:

So I have a python script (let's call it file_1.py) that overwrites the content of a text file with new content, and it works just fine. I have another python script (file_2.py) that reads the file and performs actions on the data in the file. With file_2.py I've been trying to get when the text file is edited by file_1.py and then do some stuff with the new data as soon as it's added. I looked into the subprocess module but I couldn't really figure out how to use it across different files. Here's what I have so far:

file_1.py:

with open('text_file.txt','w') as f:
    f.write(assemble(''.join(data))) # you can ignore what assemble does, this part already works.

file_2.py:

while True:
    f = open('text_file.txt','r')
    data = f.read()
    function(data)
    f.close()

我认为由于我每次循环关闭并重新打开文件,文件中的数据都会更新.但是,看来我错了,因为即使文件已更新,数据也保持不变.

那么我该怎么做呢?

I thought that since I close and reopen the file every loop, the data in the file would be updated. However, it appears I was wrong, as the data remains the same even though the file was updated.

So how can I go about doing this?

推荐答案

您是否总是用相同的数据覆盖第一个文件中的数据?我的意思是,不是随时间添加或实际更改数据?

Are you always overwiting the data in the first file, with the same data? I mean, instead of appending or actually changing the data over time?

当我改变时,我看到它在这里工作

I see it working here when I change

with open('text_file.txt','wt') as f:

with open('text_file.txt','at') as f:

然后我附加了一些数据.'w' 将覆盖,如果数据没有改变,您将一遍又一遍地看到相同的数据.

and I append some data. 'w' will overwrite and if data doesn't change you will see the same data over and over.

另一种可能性(如对 OP self-answer 的评论中所述)是在写入文件后需要使用 f.flush().尽管在关闭文件(或留下 with 块)时缓冲区会自动写入磁盘,但写入可能需要一些时间,如果在该时间之前再次读取文件,更新将不会那里(还).为了消除更新后的不确定性调用刷新,这会强制磁盘写入.

Another possibility (as discussed in the comments to OP self-answer) is the need to use f.flush() after writing to the file. Despite the buffers being written to disk automatically when closing a file (or leaving a with block), that write can take a moment, and if the file is read again before that moment, the updates will not be there (yet). To remove that uncertainty call flush after updating, wich forces the disk write.

如果您在两次阅读之间让阅读代码休眠足够长的时间(即阅读速度足够慢),则可能不需要手动刷新.但是,如果有疑问,或者以简单的方式确定,只需使用 flush().

If you sleep your reading code for enough time between readings (that is the reads are slow enough), the manual flush might not be needed. But if in doubt, or to do it the simple way and be sure, just use flush().

这篇关于获取文本文件何时被另一个程序编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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