Can I read new data from an open file without reopening it?

一笑奈何 提交于 2020-02-03 08:39:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/25413115/can-i-read-new-data-from-an-open-file-without-reopening-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!