Python 3 – os.lstat() Method
In Python programming language, os.lstat() method is used to get the status of a file or a directory. It returns a stat_result object which contains the status of the specified path. The difference between os.stat() and os.lstat() is that os.lstat() does not follow symbolic links whereas os.stat() does. This article will explain in detail the usage of the os.lstat() method.
Syntax:
os.lstat(path)
Parameters:
- path – It is the path of the file or directory which we want to get the status of. It could be a string or the output of a file object’s .name attribute.
Return Value:
- This method returns a stat_result object containing the status of the provided path.
Exceptions:
- OSError – This exception is raised when the provided path is invalid or doesn’t exist.
Example 1: Get the status of a file
import os
file_stat = os.lstat('file.txt')
print(f"File mode:{file_stat.st_mode}")
print(f"File size:{file_stat.st_size}")
print(f"Creation time:{file_stat.st_ctime}")
print(f"Last modification time:{file_stat.st_mtime}")
Output:
File mode:33188
File size:50
Creation time:1574460034.7125182
Last modification time:1574460034.7125182
Example 2: Get the status of a directory
import os
dir_path = '/home/user/'
dir_stat = os.lstat(dir_path)
print(f"Directory mode:{dir_stat.st_mode}")
print(f"Size of the directory file contents:{dir_stat.st_size}")
print(f"Creation time:{dir_stat.st_ctime}")
print(f"Last modification time:{dir_stat.st_mtime}")
Output:
Directory mode:16877
Size of the directory file contents:4096
Creation time:1529379468.0
Last modification time:1621003529.4948528
Example 3: Using try-except block to catch OSError
import os
try:
file_stat = os.lstat('file_does_not_exist.txt')
except OSError as e:
print(f"Following error occurred:{str(e)}")
Output:
Following error occurred:[Errno 2] No such file or directory: 'file_does_not_exist.txt'
In conclusion, os.lstat() is a useful method to get the status of a file or directory in Python programming language. It returns a stat_result object which consists of file status information. This method is useful in situations when we don’t want to follow symbolic links while getting file information.