深度阅读

How to get the size of a file in Python using os.path.getsize()?

作者
作者
2023年08月22日
更新时间
9.54 分钟
阅读时间
0
阅读量

To get the size of a file in Python, you can use the os.path.getsize() method from the os library. This method takes the path to the file as its input and returns the size of the file in bytes as an integer. Here is an example:

import os

filename = "/path/to/file.txt"
size = os.path.getsize(filename)
print(size)

This example gets the size of the file located at /path/to/file.txt and prints it to the console.

Note that os.path.getsize() will raise a FileNotFoundError if the file does not exist or is inaccessible. Also, some file systems may not provide an accurate size value for very large files, so the size value returned by os.path.getsize() should be treated as an estimate.

Using os.path.getsize() is useful when you need to check the size of a file before performing certain operations that may be affected by the size of the file, such as transferring or copying files between different locations or devices.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。