Python os.lstat() 方法用于检索有关文件或文件描述符的数据。这是 fstat() 在不支持符号链接的平台(如 Windows)上的别名。
与 “os.stat()” 方法不同,os.lstat() 不遵循符号链接。但是,这两种方法都用于获取文件描述符的状态。
这是 lstat 方法返回的结构 -
- st_dev - 包含文件的设备的 ID
- st_ino − inode 编号
- st_mode − 保护
- st_nlink − 硬链接的数量
- st_uid − 所有者的用户 ID
- st_gid − 所有者的组 ID
- st_rdev − 设备 ID(如果是特殊文件)
- st_size - 总大小,以字节为单位
- st_blksize − 文件系统 I/O 的块大小
- st_blocks − 分配的区块数
- st_atime - 上次访问的时间
- st_mtime − 上次修改时间
- st_ctime − 上次状态更改的时间
语法
以下是 Python lstat() 方法的语法 -
os.lstat(path)
参数
Python lstat() 方法接受单个参数 -
- path − 这是将返回其信息的文件。
返回值
Python lstat() 方法返回表示系统配置信息的 “stat_result” 对象。
例以下示例显示了 lstat() 方法的用法。在这里,我们将检索有关文件描述符的系统配置信息。
import os, sys
# Open a file
path = "newFile.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )
# Now get the touple
info = os.lstat(path)
print ("File Info :", info)
# Close opened file
os.close( fd )
print("File closed successfully")
当我们运行上述程序时,它会产生以下结果——
File Info : os.stat_result(st_mode=33204, st_ino=1077520,
st_dev=2051, st_nlink=1, st_uid=0, st_gid=1000, st_size=0,
st_atime=1712293621, st_mtime=1712293621, st_ctime=1712294859)
File closed successfully
st_dev=2051, st_nlink=1, st_uid=0, st_gid=1000, st_size=0,
st_atime=1712293621, st_mtime=1712293621, st_ctime=1712294859)
File closed successfully
例
以下示例说明了如何使用 “stat_result” 对象的属性访问有关文件描述符的系统配置信息。
import os
# Using lstat() to get the status of file
fileStat = os.lstat("foo.txt")
# Accessing the attributes of the file
print(f"File Size: {fileStat.st_size} bytes")
print(f"Last Modified Time: {fileStat.st_mtime}")
print(f"Permissions: {fileStat.st_mode}")
print ("UID of the file :%d" % fileStat.st_uid)
print ("GID of the file :%d" % fileStat.st_gid)
在运行上述程序时,它显示以下结果 -
File Size: 8 bytes
Last Modified Time: 1713241356.804322
Permissions: 33277
UID of the file :500
GID of the file :500
Last Modified Time: 1713241356.804322
Permissions: 33277
UID of the file :500
GID of the file :500