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

Consider the presence of the test.txt file with some random text in it.

Now we run the following code:

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

Now we are adding data to test.txt from some other process. Is there some way without reopening f that we can read new data?

This question is limited to Python; it is just a short code to get the point.

Edit: I tried everything I know (redness, reading, searching, etc.), but this does not update anything.

Edit: since it seems that the behavior is different depending on how the file is “added to”, I will give a more specific setting. I'm on OS X 10.9, and I'm trying to read /var/log/system.log , which syslogd is written in.

Edit: Looks like I was wrong. Using read will produce new data, but if the data is small, then you must first use flush to read it.

+4
source share
1 answer

If you read 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 descriptor with a position, reading it again will continue to read from any position at this time.

Changing the file may also affect this. Many text editors are first saved to a separate file and then copy the original. If this happens, you will not see the changes because they are in the new file. You can continue to use the existing file, but as soon as you close it, the OS will complete the deletion.

+4
source

Source: https://habr.com/ru/post/1201281/


All Articles