目录
1.使用 os.stat() 功能
获取文件状态的标准解决方案是使用 os.stat() Python 函数。它返回一个 stat_result 对象,它有一个 st_size 包含文件大小(以字节为单位)的属性。
import os
stats = os.stat('filename.ext')
print(stats.st_size)
2.使用 Path.stat() 功能
或者,使用 Python 3.4,您可以使用 Path.stat() 函数来自 pathlib 模块。它类似于 os.stat() 函数和返回 stat_result 包含有关指定路径的信息的对象。
from pathlib import Path
f = Path('filename.ext')
size = f.stat().st_size
print(size)
3.使用 os.path.getsize() 功能
另一个不错的选择是使用 os.path.getsize() 函数获取指定路径的大小(以字节为单位)。
import os
size = os.path.getsize('path\to\file\filename.ext')
print(size)
4.使用 seek() 功能
这里的思路是以只读模式打开文件,并在末尾设置文件描述符的当前位置。这可以使用 seek() 函数,它以字节为单位返回当前光标位置,从头开始。
import os
with open('path\to\file\filename.ext', 'r') as f:
size = f.seek(0, os.SEEK_END)
print(size)
这就是在 Python 中获取文件大小的全部内容。
附:Python计算一个目录下所有文件大小
首先我们可以利用os.path.getsize()方法获取文件大小,例如:
import os
print(os.path.getsize("python article"))
这样我们就得到了名为python article文件的大小.
然后我们可以利用os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表并对列表中每个文件进行遍历,并用if语句判断是否为一个文件,最后利用os.path.getsize()方法获取文件大小并对他们进行加和操作,代码如下:
for f in os.listdir("."):
if os.path.isfile(file):
sum_size += os.path.getsize(f)
最后对所获得的值进行输出,我们可以把最后的值除以1000,因为通过这个方法得到的值是字节,这样就可以得到kb的值,完整代码如下:
import os
print(os.path.getsize("python article"))
sum=0
for f in os.listdir("."):
if os.path.isfile(file):
sum += os.path.getsize(f)
print(f)
print(sum_size/1000)