Python os.stat (file_name) .st_size vs os.path.getsize (file_name)

I have two codes, both of which are designed to do the same thing - sit in a loop until the file is written. Both of them are mainly used for files received via FTP / SCP.

One version of the code uses os.stat()[stat.ST_SIZE] :

 size1,size2 = 1,0 while size1 != size2: size1 = os.stat(file_name)[stat.ST_SIZE] time.sleep(300) size2 = os.stat(file_name)[stat.ST_SIZE] 

Another version does this with os.path.getsize() :

 size1,size2 = 0,0 while True: size2 = os.path.getsize(file_name) if size1 == size2: break else: time.sleep(300) size1 = size2 

I saw several instances in which the first method reports that the sizes are the same while the file is actually still growing. Is there any main reason os.stat() will report incorrectly, but os.path.getsize() not? I do not see any errors or exceptions.

+8
python
source share
1 answer

In CPython 2.6 and 2.7, os.path.getsize() is implemented as follows:

 def getsize(filename): """Return the size of a file, reported by os.stat().""" return os.stat(filename).st_size 

This shows that there is no reason to expect the two approaches to behave differently (with the possible exception, perhaps due to different loop structures in your code).

+15
source share

All Articles