|
|
获取文件大小 三种常用方法
1. os 模块(最常用)
单位默认:字节(bytes)
- import os
- file_path = "test.txt"
- # 获取字节大小
- size_bytes = os.path.getsize(file_path)
- print("字节:", size_bytes)
- # 换算 KB、MB
- def get_file_size(path):
- size = os.path.getsize(path)
- if size < 1024:
- return f"{size} B"
- elif size < 1024 ** 2:
- return f"{size/1024:.2f} KB"
- elif size < 1024 ** 3:
- return f"{size/(1024**2):.2f} MB"
- else:
- return f"{size/(1024**3):.2f} GB"
- print(get_file_size(file_path))
复制代码
2. pathlib(Python3.4+ 面向对象,简洁推荐)
- from pathlib import Path
- p = Path("test.txt")
- size = p.stat().st_size # 字节
- print(size)
复制代码
3. 获取文件夹总大小(遍历所有文件求和)
- import os
- def get_dir_size(dir_path):
- total = 0
- for root, dirs, files in os.walk(dir_path):
- for f in files:
- fp = os.path.join(root, f)
- total += os.path.getsize(fp)
- return total
- print(get_dir_size("./文件夹"))
复制代码
|
|