Tutorials  /  Python

How to Get File Size in Python: Step-by-Step Guide

Ccentron Redaktion · December 2024 ·3 min read ·Python, Tutorial

The os module in Python provides an efficient way to obtain file size. By using the stat() function, we can retrieve various file-related information. One of the key properties of this function is st_size, which gives the file size in bytes. This tutorial demonstrates a simple program to calculate file size in both bytes and megabytes. Additionally, it explores the limitations of the dir_fd argument in the stat() function when used on Mac OS.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

File Size in Python: Basic Implementation

The Python os module provides the stat() function, where the file name is passed as an argument. The function returns a tuple structure containing the file information. Below is an example program that calculates and prints the file size in bytes and megabytes.

Console
# get file size in python
import os

file_name = "/Users/pankaj/abcdef.txt"

file_stats = os.stat(file_name)

print(file_stats)
print(f'File Size in Bytes is {file_stats.st_size}')
print(f'File Size in MegaBytes is {file_stats.st_size / (1024 * 1024)}')

Output

Below is the output of the above program:

File size in python e1734709108533If you look at the stat() function, you can pass two additional arguments: dir_fd and follow_symlinks. However, these arguments are not implemented for Mac OS. The next example demonstrates this limitation.

File Size in Python: Relative Path Example

Here is an updated program where a relative path is used. Note that this throws a NotImplementedError on Mac OS.

Console
# get file size in python
import os

file_name = "abcdef.txt"
relative_path = os.open("/Users/pankaj", os.O_RDONLY)

file_stats = os.stat(file_name, dir_fd=relative_path)

Output

Below is the output of the above program:

Code
Traceback (most recent call last): File "/Users/pankaj/.../get_file_size.py", line 7, in  file_stats = os.stat(file_name, dir_fd=relative_path) NotImplementedError: dir_fd unavailable on this platform
Python file size relative path NotImplementedError e1734709291293

Conclusion

Calculating file size in Python is straightforward using the os module's stat() function. The property st_size allows us to determine the size of a file in bytes, and with simple arithmetic, we can convert it to megabytes. However, developers need to be aware of platform-specific limitations, as demonstrated with the dir_fd argument, which is not available on Mac OS. By understanding these nuances, developers can write more robust and portable Python scripts. This tutorial highlights the potential of Python for efficient file handling while cautioning about system-specific constraints.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren