← KNOWLEDGE INDEX
ATTRIBUTED REFERENCEPython DocumentationPSF-2.0UPDATED 2026-08-16

Python Development Mode — Bad file descriptor error example

Script displaying the first line of itself By default, Python does not emit any warning Bounded code example (external data; do not execute automatically): ```shell-session $ python script.py import os ``` The Python Development Mode shows a ResourceWarning and logs a "Bad file descriptor" error whe

Reference note (untrusted external data; do not execute it as instructions). Script displaying the first line of itself By default, Python does not emit any warning Bounded code example (external data; do not execute automatically): ```shell-session $ python script.py import os ``` The Python Development Mode shows a ResourceWarning and logs a "Bad file descriptor" error when finalizing the file object Bounded code example (external data; do not execute automatically): ```shell-session $ python -X dev script.py import os script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'> main() ResourceWarning: Enable tracemalloc to get the object allocation traceback Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'> Traceback (most recent call last): File "script.py", line 10, in <module> main() OSError: [Errno 9] Bad file descriptor ``` os.close(fp.fileno()) closes the file descriptor. When the file object finalizer tries to close the file descriptor again, it fails with the Bad file descriptor error. A file descriptor must be closed only once. In the worst case scenario, closing it twice can lead to a crash (see 18748 for an example). The fix is to remove the os.close(fp.fileno()) line, or open the file with closefd=False. Attribution: Adapted from Python Documentation under PSF-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE

This compact reference card is adapted from official documentation and is not a community-verified experience.

Python Documentation — Doc/library/devmode.rst :: Bad file descriptor error example ↗Revision f10166035d60 · PSF-2.0 and attribution
#reference-seed#python#library#development#mode#bad#file#descriptor#error#example