Skip to main content

How to get the size of a file in Python

How to get the size of a file in Python.

Here's a step-by-step tutorial on how to get the size of a file in Python:

  1. First, you need to decide whether you want to get the size of a local file or a file on a remote server. The process will be slightly different for each case.

  2. To get the size of a local file, you can use the os module in Python. Start by importing it at the beginning of your script:

   import os
  1. Next, you need to specify the path to the file for which you want to get the size. You can either provide the absolute path (e.g., "C:/path/to/file.txt") or a relative path (e.g., "./file.txt" if the file is in the same directory as your script).

  2. Once you have the file path, you can use the os.path.getsize() function to get the size of the file in bytes. Pass the file path as an argument to this function:

   file_path = "path/to/your/file.txt"
file_size = os.path.getsize(file_path)

After executing this code, the variable file_size will contain the size of the file in bytes.

  1. If you want to display the file size in a more human-readable format (e.g., kilobytes, megabytes, etc.), you can define a helper function to convert the size. Here's an example:
   def convert_size(size_bytes):
# List of possible units for file size
units = ["B", "KB", "MB", "GB", "TB"]

# Find the appropriate unit for file size
unit_index = 0
while size_bytes >= 1024 and unit_index < len(units) - 1:
size_bytes /= 1024
unit_index += 1

# Format the size with two decimal places and the corresponding unit
return f"{size_bytes:.2f} {units[unit_index]}"

# Usage example
file_size_formatted = convert_size(file_size)
print(f"The file size is: {file_size_formatted}")

This helper function takes the file size in bytes as input and converts it to the most appropriate unit (e.g., kilobytes, megabytes) with two decimal places. The formatted file size can then be displayed or used as needed.

  1. If you want to get the size of a file on a remote server, you can use the requests library in Python. Start by installing it using pip:
   pip install requests
  1. After installing requests, you can import it at the beginning of your script:
   import requests
  1. To get the size of a remote file, you need to send a HEAD request to the server and retrieve the "Content-Length" header from the response. Here's an example:
   file_url = "https://example.com/path/to/remote/file.txt"
response = requests.head(file_url)
file_size = int(response.headers["Content-Length"])

After executing this code, the variable file_size will contain the size of the remote file in bytes.

  1. Similarly to the local file example, you can use the convert_size() function to format the file size in a more readable format.

And that's it! You now have a detailed step-by-step tutorial on how to get the size of a file in Python.