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
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")
If the file "file.txt" is 1000 bytes in size, the output will be:
File size: 1000 bytes
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!