Python os.stat(file_name).st_size 与 os.path.getsize(file_name) [英] Python os.stat(file_name).st_size versus os.path.getsize(file_name)

查看:69
本文介绍了Python os.stat(file_name).st_size 与 os.path.getsize(file_name)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两段代码,它们都用来做同样的事情——坐在一个循环中,直到一个文件被写入完成.它们都主要用于通过 FTP/SCP 传入的文件.

I've got two pieces of code that are both meant to do the same thing -- sit in a loop until a file is done being written to. They are both mainly used for files coming in via FTP/SCP.

一个版本的代码使用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]

另一个版本使用 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

我见过多个实例,其中使用第一种方法报告大小相同,而文件实际上仍在增长.os.stat() 会错误地报告而 os.path.getsize() 不会,是否有一些潜在的原因?我没有看到任何错误或异常返回.

I've seen multiple instances where using the first method reports that the sizes are the same while the file is actually still growing. Is there some underlying reason why os.stat() would incorrectly report while os.path.getsize() would not? I'm not seeing any errors or exceptions come back.

推荐答案

在 CPython 2.6 和 2.7 中,os.path.getsize() 实现如下:

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

由此看来,显然没有理由期望这两种方法的行为不同(除非可能是由于代码中循环的不同结构).

From this, it seems pretty clear that there is no reason to expect the two approaches to behave differently (except perhaps due to the different structures of the loops in your code).

这篇关于Python os.stat(file_name).st_size 与 os.path.getsize(file_name)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆