Python file.fileno() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
file method

Definition

The operating system tracks every open file with a small integer called a file descriptor. fileno() returns that number for a Python file object.

You rarely print it. Instead you pass it to low-level functions in the os module, such as os.fsync(), os.fstat(), and os.isatty(). The exact number depends on what else is open, so never hard-code it.

file.fileno() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).

Syntax

Call it with no arguments on an open file.

python
fd = f.fileno()
os.fsync(fd)
CallWhat it does
f.fileno()An int, usually 3 or higher for files you open.
sys.stdout.fileno()1 in a normal terminal run (stdin is 0, stderr is 2).
io.StringIO().fileno()Raises io.UnsupportedOperation: there is no OS file.

Two open files never share a descriptor at the same time, but a number is often reused after a file is closed.

Method signatures
python
file.fileno()   # -> int, the OS file descriptor
# in-memory streams (StringIO, BytesIO) raise io.UnsupportedOperation

Parameters

fileno() takes no parameters.

Return Value

Return ValueDescription
intA non-negative file descriptor. Its value depends on the process and is not portable between runs.

Python Examples

Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.

Example 1 — Inspect File Descriptors Without Printing Them

Open two files at once, check their descriptors safely, and compare with the standard streams.

python
import os
import sys
import tempfile

with tempfile.TemporaryDirectory() as folder:
    first = os.path.join(folder, "a.txt")
    second = os.path.join(folder, "b.txt")
    with open(first, "w", encoding="utf-8") as f, open(second, "wb") as g:
        fd_f, fd_g = f.fileno(), g.fileno()
        print(isinstance(fd_f, int), fd_f > 2, fd_f != fd_g)
        print(os.isatty(fd_f))

print(sys.stdin.fileno(), sys.stdout.fileno(), sys.stderr.fileno())

How It Works

  1. Safe checks. The exact descriptor varies by machine, so the example prints facts about it: it is an int, above 2, and different for each open file.
  2. Two files in one with. A comma in the with statement opens both files and closes both at the end.
  3. OS-level check. os.isatty(fd) works on the raw number and reports False for a regular file.
  4. Standard streams. Standard input, output, and error are descriptors 0, 1, and 2.

Example 2 — Commit a Ledger to Disk and Read Its Size

Flush and fsync a binary file through its descriptor, then ask the OS for its size.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "ledger.bin")
    with open(path, "wb") as f:
        f.write(b"\x10" * 64)
        f.flush()
        os.fsync(f.fileno())
        info = os.fstat(f.fileno())
        print(info.st_size, "bytes are safely on disk")
        print(info.st_size == os.path.getsize(path))

How It Works

  1. Python buffer first. flush() hands the 64 bytes to the operating system.
  2. OS cache next. os.fsync(f.fileno()) asks the OS to write its cache to the storage device.
  3. Stat by descriptor. os.fstat() reads the file's metadata through the descriptor; st_size matches the path-based size.

Example 3 — Handle Streams Without a File Descriptor

In-memory streams and closed files cannot give a descriptor; catch the specific errors.

python
import io
import os
import tempfile

for stream in (io.StringIO("notes"), io.BytesIO(b"notes")):
    try:
        stream.fileno()
    except io.UnsupportedOperation:
        print(type(stream).__name__, "has no file descriptor")

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "closed.txt")
    with open(path, "w", encoding="utf-8") as f:
        f.write("done\n")
    try:
        f.fileno()
    except ValueError:
        print("fileno() on a closed file raises ValueError")

How It Works

  1. Memory only. io.StringIO and io.BytesIO live entirely in Python, so there is no OS descriptor to return.
  2. Specific exception. They raise io.UnsupportedOperation, which code can catch to fall back to a slower path.
  3. Closed file. After the with block the descriptor is released, and fileno() raises ValueError.

Frequently Asked Questions

It is the small integer the operating system uses to identify an open file. f.fileno() returns it so you can call os functions such as os.fsync() and os.fstat().
Descriptors 0, 1, and 2 are normally taken by standard input, output, and error, so the first file you open usually gets 3. Never rely on the exact value.
It has the method, but calling it raises io.UnsupportedOperation, because the data lives only in memory.
Call f.flush() and then os.fsync(f.fileno()). flush() empties Python's buffer and fsync() asks the OS to commit its cache.
Avoid it. The file object would still think it is open and may later close a reused descriptor. Call f.close() instead.

Next: file.flush()

Push buffered data from Python down to the operating system without closing the file.

flush() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful