Python os.path.getsize() 方法用于检索文件大小(以字节为单位)。它返回一个整数,表示指定文件的大小。
如果指定的路径不存在,或者存在阻止访问该路径的权限问题,该方法将分别引发 FileNotFoundError 或 PermissionError。
语法
以下是 Python os.path.getsize() 方法的基本语法 -
参数
此方法接受一个字符串作为参数,该参数表示要检索其大小的文件的路径。
返回值
该方法返回一个整数,表示文件大小(以字节为单位)。
例在以下示例中,我们将检索位于给定路径“file_Path”处的文件大小(以字节为单位)-
输出
获得的输出如下 -
The size of the file is: 873
例
在这里,我们检索当前目录的大小并以字节为单位打印 -
输出
以下是上述代码的输出 -
The size of the current directory is: 16384
例
此示例检索位于 “/home/lenovo/symlink” 的符号链接的大小,并以字节为单位打印它 -
输出
我们得到的输出如下所示 -
The size of the symbolic link is: 53
例
如果我们尝试检索不存在的文件路径 “/non/existent/path” 的大小,getsize() 方法会引发 “FileNotFoundError” -
输出
生成的结果如下所示 -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
size = os.path.getsize(link_path)
File "<frozen genericpath>", line 62, in getsize
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
size = os.path.getsize(link_path)
File "<frozen genericpath>", line 62, in getsize
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'