How to get file size in Python?

How to get file size in Python?

To get the size of a file in Python, you can use the os module's stat function. Here's a step-by-step guide:

Using the os Module:

  1. Import the required module:

    import os 
  2. Get the size of the file:

    file_path = "path_to_your_file.txt" file_size = os.stat(file_path).st_size print(f"File Size is: {file_size} bytes") 

The os.stat(file_path).st_size returns the size of the file in bytes.

Convert Bytes to KB, MB, GB, etc.:

If you want the size in units other than bytes (like KB, MB, or GB), you can create a function for that:

def convert_bytes(num): """ Convert bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return f"{num:3.2f} {unit}" num /= 1024.0 file_size_bytes = os.stat(file_path).st_size print(f"File Size is: {convert_bytes(file_size_bytes)}") 

This function will give a more human-readable format of the file size.


More Tags

subreport interface amazon-web-services istanbul jframe genson vcf-vcard sdwebimage click angular-routing

More Programming Guides

Other Guides

More Programming Examples