python 算文件大小
Python 是一种高级编程语言,非常合适用于处理文件。在 Python 中,我们可使用各种函数和库来计算文件大小。
import os def get_file_size(file_path): # 使用 os.path.getsize() 函数获得文件大小 size = os.path.getsize(file_path) # 判断文件大小并转换为易读的字符串情势 if size< 1024: return f"{size} B" elif size >= 1024 and size< 1024*1024: return f"{size/1024:.2f} KB" elif size >= 1024*1024 and size< 1024*1024*1024: return f"{size/1024/1024:.2f} MB" else: return f"{size/1024/1024/1024:.2f} GB" # 调用函数获取文件大小 file_path = "example.txt" file_size = get_file_size(file_path) print(f"The size of {file_path} is {file_size}.")
在上面的代码中,我们使用了 Python 中的 os.path.getsize() 函数来获得文件大小。该函数返回一个整数,表示文件的字节数。我们再根据字节数来判断文件的大小,并将其转换为易读的字符串情势。
例如,对一个大小为 25165824 字节的文件(即 24 MB),我们将其转换为字符串 "24.00 MB"。
总之,使用 Python 来计算文件大小非常容易,只需要使用 os.path.getsize() 函数便可。而将文件大小转换为易读的字符串情势,则需要根据实际情况进行判断和计算。
文章来源:丸子建站
文章标题:python 算文件大小
https://www.wanzijz.com/view/89576.html