How do I check file size in Python?
To check the size of a file in Python, you can use the os
module to get the size of the file in bytes.
Here's an example of how you can use the os.path.getsize()
function to get the size of a file:
import os
# Get the size of the file in bytes
size = os.path.getsize('file.txt')
print(f'Size of file: {size} bytes')
This will print the size of the file in bytes. You can use the os.path.getsize()
function on any file that you have read access to.
If you want to get the size of a file in a different unit, such as kilobytes or megabytes, you can divide the size in bytes by the appropriate conversion factor. For example, to get the size of a file in kilobytes, you can divide the size in bytes by 1024.
Here's an example of how you can use this to get the size of a file in kilobytes:
import os
# Get the size of the file in bytes
size = os.path.getsize('file.txt')
# Convert the size to kilobytes
size_kb = size / 1024
print(f'Size of file: {size_kb:.2f} KB')
This will print