diff --git a/cupsconnection.c b/cupsconnection.c
index d11ada5..69037b1 100644
--- a/cupsconnection.c
+++ b/cupsconnection.c
@@ -2156,10 +2156,14 @@ Connection_getFile (Connection *self, PyObject *args, PyObject *kwds)
     return NULL;
   }
 
+#if PY_MAJOR_VERSION >= 3
+  fd = PyObject_AsFileDescriptor(fileobj);
+#else
   if (fileobj) {
     FILE *f = PyFile_AsFile (fileobj);
     fd = fileno (f);
   }
+#endif
 
   if (filename) {
     debugprintf ("-> Connection_getFile(%s, %s)\n", resource, filename);
@@ -2205,10 +2209,14 @@ Connection_putFile (Connection *self, PyObject *args, PyObject *kwds)
     return NULL;
   }
 
+#if PY_MAJOR_VERSION >= 3
+  fd = PyObject_AsFileDescriptor(fileobj);
+#else
   if (fileobj) {
     FILE *f = PyFile_AsFile (fileobj);
     fd = fileno (f);
   }
+#endif
 
   if (filename) {
     debugprintf ("-> Connection_putFile(%s, %s)\n", resource, filename);
diff --git a/cupsppd.c b/cupsppd.c
index 79e893d..80b5145 100644
--- a/cupsppd.c
+++ b/cupsppd.c
@@ -630,7 +630,12 @@ PPD_emit (PPD *self, PyObject *args)
   if (!PyArg_ParseTuple (args, "Oi", &pyFile, &section))
     return NULL;
 
+#if PY_MAJOR_VERSION >= 3
+  int fd = PyObject_AsFileDescriptor(pyFile);
+  f = fdopen(fd, "a+");
+#else
   f = PyFile_AsFile(pyFile);
+#endif
   if (!f)
     return NULL;
 
@@ -655,7 +660,12 @@ PPD_emitAfterOrder (PPD *self, PyObject *args)
   if (!PyArg_ParseTuple (args, "Oiif", &pyFile, &section, &limit, &min_order))
     return NULL;
 
+#if PY_MAJOR_VERSION >= 3
+  int fd = PyObject_AsFileDescriptor(pyFile);
+  f = fdopen(fd, "a+");
+#else
   f = PyFile_AsFile(pyFile);
+#endif
   if (!f)
     return NULL;
 
@@ -708,7 +718,12 @@ PPD_emitJCL (PPD *self, PyObject *args)
     return NULL;
   }
 
+#if PY_MAJOR_VERSION >= 3
+  int fd = PyObject_AsFileDescriptor(pyFile);
+  f = fdopen(fd, "a+");
+#else
   f = PyFile_AsFile(pyFile);
+#endif
   if (!f)
     return NULL;
 
@@ -733,7 +748,12 @@ PPD_emitJCLEnd (PPD *self, PyObject *args)
   if (!PyArg_ParseTuple (args, "O", &pyFile))
     return NULL;
 
+#if PY_MAJOR_VERSION >= 3
+  int fd = PyObject_AsFileDescriptor(pyFile);
+  f = fdopen(fd, "a+");
+#else
   f = PyFile_AsFile(pyFile);
+#endif
   if (!f)
     return NULL;