Home > Backend Development > Python Tutorial > How Can I Get a File\'s Size in Python?

How Can I Get a File\'s Size in Python?

DDD
Release: 2024-11-27 15:52:11
Original
859 people have browsed it

How Can I Get a File's Size in Python?

Checking File Size in Python

Determining the size of a file is a common task in programming. Python provides several ways to accomplish this, with the most straightforward being the use of the os.path.getsize() function.

Using os.path.getsize()

To get the size of a file in Python using os.path.getsize(), simply pass the file path as an argument to the function. The output will be the file size in bytes.

import os
file_size = os.path.getsize("/path/to/file.mp3")
print(file_size)  # Output: 2071611
Copy after login

Example Output

The following code demonstrates how to use os.path.getsize() to check the size of a file:

import os

# Get the size of a file in bytes
file_size = os.path.getsize("file.txt")

# Print the file size
print("File size:", file_size, "bytes")
Copy after login

If the file "file.txt" is 1000 bytes in size, the output will be:

File size: 1000 bytes
Copy after login

Note:

The size returned by os.path.getsize() is always in bytes. If you need the size in a different unit, such as kilobytes or megabytes, you will need to perform the appropriate conversion.

The above is the detailed content of How Can I Get a File\'s Size in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template