Python os.lstat() Method

Python os.lstat() Method

  1. Syntax of Python os.lstat() Method
  2. Example Codes: Working With the os.lstat() Method
  3. Example Codes: Retrieve Some Elements of the os.lstat() Method

Python os.lstat() method is an efficient way of finding information about a file. It is an alias to the os.stat() method that doesn’t support symbolic paths.

Syntax of Python os.lstat() Method

os.lstat(path address)

Parameters

path address It is an address object of a file system path or a symlink. The object can either be an str or bytes.

Return

The return type of this method is all the information about the specified file. The following details are returned.

Return Type Description
st_dev Device ID where the file resides.
st_ino inode number of the file system.
st_mode Permission access to the file.
st_nlink Number of hard links for the file.
st_uid User ID of the file’s owner.
st_gid Group ID of the file’s owner
st_rdev Device ID of a special file.
st_size Total file size in bytes.
st_blksize Total block size for the file system.
st_blocks Number of blocks allocated to the file.
st_atime Last time, the file was accessed.
st_mtime Last time, the file was modified.
st_ctime Last time, the file status was changed.

Example Codes: Working With the os.lstat() Method

import os
import sys

path ="/home/File.txt"

fd = os.open(path, os.O_RDWR|os.O_CREAT)
os.close(fd)
file_info = os.lstat(path)

print ("The file info is:", file_info)

Output:

The file info is: os.stat_result(st_mode=33279, st_ino=303997, st_dev=2049, st_nlink=1, st_uid=0, st_gid=0, st_size=33, st_atime=1660394495, st_mtime=1660394495, st_ctime=1660394495)

The method os.lstat() can support any path relative to a given file descriptor.

Example Codes: Retrieve Some Elements of the os.lstat() Method

import os
import sys

path ="/home/File.txt"
fd = os.open(path, os.O_RDWR|os.O_CREAT)
os.close(fd)
file_info = os.lstat(path)

print ("The device ID is:", file_info[2])
print ("The user ID is:", file_info[4])

Output:

The device ID is: 2049
The user ID is: 0

The information returned by the os.lstat() method is in the form of an array, starting from the index number 0. Some elements of this method can be retrieved by specifying the index number.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method