我可以从一个打开的文件中读取新的数据而无需重新打开它吗? [英] Can I read new data from an open file without reopening it?

查看:176
本文介绍了我可以从一个打开的文件中读取新的数据而无需重新打开它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑有一个文件 test.txt 和一些随机文本。



现在我们运行以下code:

  f = open('test.txt','r')
f.read()
$ / code>

现在我们将数据追加到 test.txt 一些其他的过程。有没有重新打开 f 我们可以读取新数据?



这个问题仅限于Python,它只是短小的代码需要得到的点。

编辑:我已经尝试了我所知道的一切(冲洗,阅读,寻求等),但似乎并没有更新任何东西。



编辑:由于看起来行为是不同的取决于文件是如何附加到,我会给一个更具体的设置。我在OS X 10.9上,我试图阅读由 syslogd 写的 /var/log/system.log code>。



编辑:看来我错了。使用读取会得到新的数据,但是如果数据很小,那么必须首先使用 flush 才能阅读它。

解决方案

如果您再次阅读 f 将得到更多的数据。

  f = open('my_file')
print(f.read())
#in bash:echo'more data'>> my_file $ b $ print(f.read())

f 基本上是一个带有位置的文件句柄,再次读取它将继续读取当前的位置。

这也可以是受 修改文件的影响。许多文本编辑器将首先保存到一个单独的文件,然后复制原件。如果发生这种情况,您将不会看到在新文件中的更改。你可以继续使用现有的文件,但只要你关闭它,操作系统将完成删除。


Consider having a file test.txt with some random text in it.

Now we run the following code:

f = open('test.txt', 'r')
f.read()

Now we append data onto test.txt from some other process. Is there some way without reopening f that we can read the new data?

This question is limited to Python, it is just short amount of code needed to get the point across.

Edit: I have tried everything I know (flushing, reading, seeking, etc) but that doesn't seem to update anything.

Edit: Since it seems that behavior is different depending on how the file is "appended to", I will give a more specific setup. I'm on OS X 10.9, and I'm trying to read /var/log/system.log which is written to by syslogd.

Edit: It appears I was incorrect. Using a read will pull new data, but if the data is small then a flush must be used first to be able to read it.

解决方案

If you read from f again, you will get more data.

f = open('my_file')
print(f.read())
# in bash: echo 'more data' >> my_file
print(f.read())

f is basically a file handle with a position, reading from it again will just continue to read from whatever the position currently is.

This can also be affected by what is modifying the file. Many text editors will save to a separate file first, then copy over the original. If this happens, you will not see the changes as they are in a new file. You many be able to continue using the existing file, but as soon as you close it the OS will finalize the delete.

这篇关于我可以从一个打开的文件中读取新的数据而无需重新打开它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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