Python| os.path.size() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.getsize()
方法用于检查指定路径的大小。它以字节为单位返回指定路径的大小。如果文件不存在或无法访问,该方法会引发OSError 。
Syntax: os.path.getsize(path)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a integer value which represents the size of specified path in bytes.
代码 #1:使用 os.path.getsize() 方法
# Python program to explain os.path.getsize() method
# importing os module
import os
# Path
path = '/home/User/Desktop/file.txt'
# Get the size (in bytes)
# of specified path
size = os.path.getsize(path)
# Print the size (in bytes)
# of specified path
print("Size (In bytes) of '%s':" %path, size)
输出:
Size (In bytes) of '/home/User/Desktop/file.txt': 243
代码 #2:使用 os.path.getsize() 方法时处理错误
# Python program to explain os.path.getsize() method
# importing os module
import os
# Path
path = '/home/User/Desktop/file2.txt'
# Get the size (in bytes)
# of specified path
try :
size = os.path.getsize(path)
except OSError :
print("Path '%s' does not exists or is inaccessible" %path)
sys.exit()
# Print the size (in bytes)
# of specified path
print("Size (In bytes) of '% s':" % path, size)
输出:
Path '/home/User/Desktop/file2.txt' does not exists or is inaccessible
参考: https://docs。 Python.org/3/library/os.path.html