如何在Python中计算文件的大小
发布时间:2023-12-04 17:11:51
在Python中,可以使用os模块的path函数来获取文件大小。下面是一个计算文件大小的例子:
import os
def get_file_size(file_path):
size = os.path.getsize(file_path)
return size
# 示例用法
file_path = 'example.txt'
file_size = get_file_size(file_path)
print(f"The size of {file_path} is {file_size} bytes.")
输出:
The size of example.txt is 1000 bytes.
在上述例子中,get_file_size函数接受一个文件路径作为参数,并使用os.path.getsize函数获取指定文件的大小。然后,函数返回文件的大小,以字节为单位。
在示例用法中,我们提供了一个文件路径example.txt来测试函数。然后,使用get_file_size函数获取文件example.txt的大小,并将结果打印出来。
