本文目录导读:

- 方法1:使用
os.path.getsize()(最常用) - 方法2:使用
os.stat() - 方法3:使用
pathlib(推荐现代写法) - 方法4:使用
seek()和tell() - 实用案例:检查多个文件大小
- 完整示例:文件大小工具类
- 注意事项
- 推荐使用
在Python中获取文件大小有多种方法,下面介绍几种常用的方式:
方法1:使用 os.path.getsize()(最常用)
import os
# 获取文件大小(字节)
file_path = "example.txt"
file_size = os.path.getsize(file_path)
print(f"文件大小:{file_size} 字节")
# 转换为更易读的格式
def get_file_size_readable(file_path):
size_bytes = os.path.getsize(file_path)
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_bytes < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
print(f"可读格式:{get_file_size_readable('example.txt')}")
方法2:使用 os.stat()
import os
file_path = "example.txt"
file_stats = os.stat(file_path)
file_size = file_stats.st_size
print(f"文件大小:{file_size} 字节")
print(f"其他信息:")
print(f" 最后修改时间:{file_stats.st_mtime}")
print(f" 最后访问时间:{file_stats.st_atime}")
print(f" 权限模式:{oct(file_stats.st_mode)}")
方法3:使用 pathlib(推荐现代写法)
from pathlib import Path
# 获取文件大小
file_path = Path("example.txt")
file_size = file_path.stat().st_size
print(f"文件大小:{file_size} 字节")
# 或者直接使用 resolve()
file_size = file_path.resolve().stat().st_size
方法4:使用 seek() 和 tell()
with open("example.txt", "rb") as file:
# 移动到文件末尾
file.seek(0, 2) # 2 表示从文件末尾开始
file_size = file.tell()
print(f"文件大小:{file_size} 字节")
实用案例:检查多个文件大小
import os
from pathlib import Path
def check_files_in_directory(directory):
"""检查目录中所有文件的大小"""
dir_path = Path(directory)
for file_path in dir_path.glob("*"):
if file_path.is_file():
size = file_path.stat().st_size
# 格式化输出
if size < 1024:
size_str = f"{size} B"
elif size < 1024 * 1024:
size_str = f"{size/1024:.2f} KB"
else:
size_str = f"{size/(1024*1024):.2f} MB"
print(f"{file_path.name}: {size_str}")
# 使用示例
check_files_in_directory("./")
完整示例:文件大小工具类
import os
from pathlib import Path
from typing import Union
class FileSizeChecker:
"""文件大小检查工具类"""
@staticmethod
def get_size(file_path: Union[str, Path]) -> int:
"""获取文件大小(字节)"""
return os.path.getsize(str(file_path))
@staticmethod
def format_size(size_bytes: int) -> str:
"""格式化文件大小显示"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_bytes < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} PB"
@staticmethod
def compare_sizes(file1: str, file2: str) -> dict:
"""比较两个文件的大小"""
size1 = FileSizeChecker.get_size(file1)
size2 = FileSizeChecker.get_size(file2)
return {
"file1": {"name": file1, "size": size1, "formatted": FileSizeChecker.format_size(size1)},
"file2": {"name": file2, "size": size2, "formatted": FileSizeChecker.format_size(size2)},
"difference": abs(size1 - size2),
"larger": file1 if size1 > size2 else file2
}
# 使用示例
checker = FileSizeChecker()
# 获取单个文件大小
size = checker.get_size("example.txt")
print(f"文件大小:{checker.format_size(size)}")
# 比较两个文件
result = checker.compare_sizes("file1.txt", "file2.txt")
print(f"较大的文件:{result['larger']}")
print(f"大小差异:{checker.format_size(result['difference'])}")
注意事项
- 路径处理:确保文件路径正确,否则会抛出
FileNotFoundError - 权限问题:如果没有读取权限,会抛出
PermissionError - 大文件处理:对于非常大的文件,
seek()方法可能更高效 - 编码问题:使用
seek()方法时建议使用二进制模式"rb"
推荐使用
- 简单获取:使用
os.path.getsize() - 现代Python:使用
Path.stat().st_size - 需要其他信息:使用
os.stat()
这些方法都能准确获取文件大小,选择哪种取决于你的具体需求和代码风格。