gpt4 book ai didi

python - os.path.getsize(path) 或 os.stat

转载 作者:行者123 更新时间:2023-12-01 20:26:53 25 4
gpt4 key购买 nike

os.path.getsize(path) 和 os.stat 之间有什么不同?哪一个最适合在 python 3 中使用?我们什么时候使用它们?为什么我们有两个相同的解决方案?我发现this回答但我无法理解这句话的意思:

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)

具体来说,为什么我们有两种方法,有什么不同?

最佳答案

stat是一个 POSIX 系统调用(可在 Linux、Unix 甚至 Windows 上使用),它返回一堆信息(大小、类型、保护位...)

Python 必须在某个时刻调用它来获取大小 ( and it does ),但没有系统调用来获取大小。

所以它们在性能方面是相同的(使用stat可能更快,但这只是多了1个函数调用,所以与I/O无关)。就是这样os.path.getsize写起来比较简单。

也就是说,能够调用 os.path.getsize您必须确保该路径实际上是一个文件。当在目录上调用时,getsize返回一些值(在 Windows 上测试),该值可能与节点的大小有关,因此您必须使用 os.path.isfile第一:再次调用 os.stat .

最后,如果你想最大化性能,你必须使用 os.stat ,检查 infos 看看 path 是否是一个文件,然后使用 st_size信息。这样您就可以调用 stat仅一次。

如果您使用os.walk扫描目录,您会看到更多隐藏的 stat来电,所以查看os.scandir (Python 3.5)。

相关:

关于python - os.path.getsize(path) 或 os.stat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com