[Tutor] how to check if a file is being used by another person or application before writing to it?

Hugo González Monteverde hugonz at h-lab.net
Wed Dec 1 01:46:43 CET 2004


Maybe you can accomplish this using the stat function in the os module.

say:

import os
filename = "foo.txt"
mystat = os.stat(filename)

#Stat has a number of attributes, such as
mystat.st_atime #time of most recent access

atime = time.ctime(mystat.st_atime)
print atime
'Wed Nov 17 23:51:11 2004'

The size of the file is in the st_size attribute of the stat object. It 
is in bytes... You may use this, but I guess st_atime is a better 
parameter to check for that. You could keep the last access time and 
then check if it has changed.

As for the "how to know if the file has already been opened by another 
process" I really do not know. I guess that's what file locking if 
for... maybe someone can step in and clarify a bit...

Hugo

>  
> similarly is there a way to check if a file has been written to? I 
> suppose I would do something like periodically check the size of a 
> particular file and if it increased then I would know it was written to. 
> I didn't see anything in the python documentation for geting the size of 
> a file. how is this normally performed?
>  
> thanks.
>  
> Jeff
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list