In this lesson, you will learn how the operating system uses integer-based file descriptors to keep track of open files and manage system-level resources.
What is a File Descriptor?
Up until now, you have interacted with files using high-level Python objects like pathlib.Path or the open() function. While these are convenient, the operating system (OS) doesn't actually see a "file object" when you read or write data. Instead, the OS maintains a table for every process that maps small, non-negative integers—called file descriptors—to open files or hardware devices.
When you ask Python to open a file, the OS assigns an integer index to that specific connection. Any subsequent read or write operation you perform refers to that integer so the OS knows exactly which file resource you are targeting.
Seeing it in Practice
You can peek behind the curtain by accessing the fileno() method of a file object. This method exposes the raw integer the OS has assigned to that open file stream:
# Open a file in write mode
with open("example.txt", "w") as f:
# Retrieve the low-level integer file descriptor
fd = f.fileno()
print(f"The operating system assigned file descriptor: {fd}")
In most systems, you will see 3 (or higher). This is because the integers 0, 1, and 2 are reserved by the OS for standard system processes:
0: Standard Input (stdin)1: Standard Output (stdout)2: Standard Error (stderr)
Why does this matter?
By using integers to track files, the OS can maintain a highly efficient, lightweight index of every resource your program is accessing. When you close a file, that integer becomes "free," and the OS can recycle it for the next file you open. This low-level management is why resource cleanup (like using finally blocks or context managers) is so critical; if you open files without closing them, your program will eventually exhaust its limit of available file descriptors, causing the OS to block any further file access.
Key Takeaway: File descriptors are integer "handles" that the operating system uses as a lookup key to manage and track the state of your open file resources.