get size of file in python through pathlib or shutils or os
- User
get size of file in python through pathlib or shutils or os
- Assistant
You can get the size of a file in Python using several libraries, including
pathlib,shutil, andos. Below are examples for each of these libraries.Using
pathlibpythonfrom pathlib import Path file_path = Path('path/to/your/file.txt') file_size = file_path.stat().st_size # Size in bytes print(f"File size: {file_size} bytes")Using
ospythonimport os file_path = 'path/to/your/file.txt' file_size = os.path.getsize(file_path) # Size in bytes print(f"File size: {file_size} bytes") - User
Pathlib size in MB
- Assistant
To get the size of a file in megabytes (MB) using
pathlib, you can simply divide the size in bytes by ( 1,024 \times 1,024 ) (or ( 1024^2 )). Here's how you can do it:pythonfrom pathlib import Path file_path = Path('path/to/your/file.txt') file_size_bytes = file_path.stat().st_size # Size in bytes # Convert to MB file_size_MB = file_size_bytes / (1024 * 1024) print(f"File size: {file_size_MB:.2f} MB")Explanation:
file_path.stat().st_sizeretrieves the size of the file in bytes.- Dividing by ( 1024 \times 1024 ) converts bytes to megabytes.
- Formatting with
:.2fensures the output shows two decimal places.
This will give you the size of the file in megabytes with a precision of two decimal places.