Question

How can I get the file size with Python?

Answer and Explanation

You can retrieve the size of a file using Python with a few different approaches. The most common method involves the os module, particularly the os.path.getsize() function. Here's how:

1. Using `os.path.getsize()`:

- This is the simplest method to get the file size in bytes.

- It requires importing the os module.

- The function returns the size of the file in bytes.

Example:

import os

file_path = "example.txt" # Replace with your file path

try:
  file_size_bytes = os.path.getsize(file_path)
  print(f"The file size of {file_path} is: {file_size_bytes} bytes")
except FileNotFoundError:
  print(f"Error: File not found at {file_path}")
except Exception as e:
  print(f"An error occurred: {e}")

2. Converting Bytes to Other Units (KB, MB, GB):

- Often, you'll want to display the file size in a more human-readable format, such as kilobytes, megabytes or gigabytes.

- You can do this by dividing the file size in bytes by the appropriate factor (1024 for KB, 1024^2 for MB, 1024^3 for GB).

Example:

import os

def convert_size(size_bytes):
  if size_bytes >= 10243:
    return f"{size_bytes / (10243):.2f} GB"
  elif size_bytes >= 10242:
    return f"{size_bytes / (10242):.2f} MB"
  elif size_bytes >= 1024:
    return f"{size_bytes / 1024:.2f} KB"
  else:
    return f"{size_bytes} bytes"

file_path = "example.txt" # Replace with your file path

try:
  file_size_bytes = os.path.getsize(file_path)
  formatted_size = convert_size(file_size_bytes)
  print(f"The file size of {file_path} is: {formatted_size}")
except FileNotFoundError:
  print(f"Error: File not found at {file_path}")
except Exception as e:
  print(f"An error occurred: {e}")

3. Error Handling:

- It's good practice to include error handling to deal with scenarios where the file might not be found, or other issues might arise.

- The examples above show simple try and except block for basic error handling.

These methods are fundamental for various file-handling operations in Python, such as checking file sizes before uploading or downloading, or managing disk space. Always remember to handle potential errors and provide clear messages to users.

More questions