在Python中,os.path.getsize() 函数是获取文件字节数最直接和最简单的方法。它返回指定路径的文件大小,以字节为单位。
import os
# 获取文件路径
file_path = 'example.txt'
# 获取文件字节数
file_size = os.path.getsize(file_path)
print(f"文件 '{file_path}' 的字节数为: {file_size} 字节")FileNotFoundError。通过使用 with 语句和文件的 read() 方法,可以逐字符读取文件,并在读取过程中计算总字节数。
def get_file_size_by_read(file_path): with open(file_path, 'rb') as file: # 使用二进制模式打开文件 file_size = 0 while True: data = file.read(1024) # 每次读取1024字节 if not data: break file_size += len(data) return file_size
# 获取文件路径
file_path = 'example.txt'
# 获取文件字节数
file_size = get_file_size_by_read(file_path)
print(f"文件 '{file_path}' 的字节数为: {file_size} 字节")rb(二进制读取)模式打开文件。当处理大文件时,使用生成器是一种内存高效的方法。以下是一个生成器的例子,用于逐行读取文件并计算总字节数。
def get_file_size_by_lines(file_path): with open(file_path, 'rb') as file: file_size = 0 for line in file: file_size += len(line) return file_size
# 获取文件路径
file_path = 'example.txt'
# 获取文件字节数
file_size = get_file_size_by_lines(file_path)
print(f"文件 '{file_path}' 的字节数为: {file_size} 字节")rb 模式打开文件。os.stat() 函数可以返回与文件相关的元信息,包括文件大小。这可以通过 st_size 属性访问。
import os
# 获取文件路径
file_path = 'example.txt'
# 获取文件字节数
file_size = os.stat(file_path).st_size
print(f"文件 '{file_path}' 的字节数为: {file_size} 字节")FileNotFoundError。shutil.getsize() 函数是另一个获取文件大小的函数,它提供了一个更简洁的接口。
import shutil
# 获取文件路径
file_path = 'example.txt'
# 获取文件字节数
file_size = shutil.getsize(file_path)
print(f"文件 '{file_path}' 的字节数为: {file_size} 字节")FileNotFoundError。通过以上五种方法,你可以根据需要选择最适合你的方法来计算Python中的文件字节数。