File Polling (Rereading)

Jeremy Jones zanesdad at bellsouth.net
Thu Oct 21 14:09:07 CEST 2004


Daniel Mueller wrote:

> Diez B. Roggisch wrote:
>
>> If you're only interested in the content if the file has actually
>> changed - thats a totally different animal,
>
>
> Good to hear! i only need the changes! do you have code examples?
>
>> and is under unix doable using
>> stat-calls (somewhere in the os module). I'm not sure how much that 
>> extends
>> to windows, but I'm pretty much confident that there is similar stuff
>> available.
>
>
> im programming under Linux
>
>
>
You could do something like this.

Here is something that is writing to a file:

In [5]: f = open('/tmp/foobar.txt', 'w')

In [6]: import time

In [7]: for t in range(10):
   ...:     f.write('this is entry %s\n' % t)
   ...:     f.flush()
   ...:     time.sleep(10)



Here is something reading from the same file (with its output):

In [4]: import time

In [5]: f = open('/tmp/foobar.txt', 'r')

In [6]: for t in range(10):
   ...:     print "read this from file: %s" % f.read()
   ...:     time.sleep(10)
   ...:
read this from file: this is entry 0
this is entry 1

read this from file:
read this from file: this is entry 2

read this from file: this is entry 3

read this from file: this is entry 4

read this from file: this is entry 5

read this from file: this is entry 6

read this from file: this is entry 7

read this from file: this is entry 8

read this from file: this is entry 9


If you open a file in read mode and don't close it, you can just keep on 
giving the read() operation on it.  No need to close it and then re-open 
it.  Although, if you did want/need to close it, you could always store 
where the end of the file was when you last had it opened as well as the 
last modification time and when you need to check the file again, just 
stat it and if it has changed, open it, seek to the former end, then 
start reading from there.....


Jeremy Jones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20041021/b1597bad/attachment.html>


More information about the Python-list mailing list