在Windows上使用os.stat()

8

os.stat() 在 Windows 上有哪些填充虚拟值的字段呢?具体而言,st_ino 在 Windows 上代表什么呢?Python 文档未对此作出明确说明。

是否有人能在 Windows 上运行交互式 Python 会话并让我知道呢?我没有 Windows 机器所以不能自己做这件事。

6个回答

4

st_inost_devst_nlinkst_uidst_gid是Windows 7 SP1到Python 2.7.11版本中的虚拟变量。

import os; os.stat('Desktop\test.txt')
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=293L, st_atime=1448376581L, st_mtime=1451782006L, st_ctime=1448376581L)

然而,在Windows 7 SP1中,从Python 3.5.1开始,它们似乎被填充了有意义的值:

import os; os.stat('Desktop\test.txt')
os.stat_result(st_mode=33206, st_ino=17732923532870243, st_dev=2289627604, st_nlink=2, st_uid=0, st_gid=0, st_size=293, st_atime=1448376581, st_mtime=1451782006, st_ctime=1448376581)

Python文档中关于此主题的内容会告诉一个理智的用户要避免在Windows中使用os.stat,因为没有任何保证任何字段将始终/永远准确。实际上,看起来st_sizest_atimest_mtimest_ctime通常是准确的,如果不总是准确的。其他字段取决于至少Python版本,可能还有Windows版本和其他因素。

3

在Python 3.3.4中

>>> os.stat('.')
nt.stat_result(st_mode=16895, st_ino=1407374883604316, st_dev=0, st_nlink=1, st_uid=0,
st_gid=0, st_size=4096, st_atime=1392476826, st_mtime=1392476826, st_ctime=1392374365)

与旧版本不同,st_ino已实现。


从3.4.0版本开始,st_dev已经被实现。 - drdrez

2
这是一个测试运行:

C:\WINDOWS>echo test > test.txt

C:\WINDOWS>python
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.stat('test.txt')
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=
0, st_size=7L, st_atime=1299861919L, st_mtime=1299861919L, st_ctime=1299861919L)

>>>

1

Python 3.1.2 说:

>>> os.stat("C:\\autoexec.bat")
nt.stat_result(st_mode=33279, st_ino=0, st_dev=0, st_nlink=0, st_uid=0, st_gid=0,
st_size=0, st_atime=1150614982, st_mtime=1150614982, st_ctime=1150614982)

0

Python 3:

>>> os.stat( r'C:\Users\poke\Desktop\test.txt' )
nt.stat_result(st_mode=33206, st_ino=0, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=252, st_atime=1299861949, st_mtime=1298245084, st_ctime=1299861949)

还需要什么吗?


-2

我在Python 3.4中运行了os.stat

这是我使用的代码

import os


myPath = os.path.expanduser("~")
os.chdir(myPath)

files = os.listdir()

for file in files:
    info = os.stat(file)
    print ("{0:>20} {1:>8}".format(file, info.st_size))

4
没有输出,这就变得毫无用处了。 - Teepeemm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接