Issue #20037: Avoid crashes when doing text I/O late at interpreter shutdown.
diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c
index 0e1e709..cbb2daf 100644
--- a/Modules/_io/fileio.c
+++ b/Modules/_io/fileio.c
@@ -493,8 +493,10 @@
 static PyObject *
 err_mode(char *action)
 {
-    PyErr_Format(IO_STATE->unsupported_operation,
-                 "File not open for %s", action);
+    _PyIO_State *state = IO_STATE();
+    if (state != NULL)
+        PyErr_Format(state->unsupported_operation,
+                     "File not open for %s", action);
     return NULL;
 }