檔案物件 (File Objects)¶
這些 API 是用於內建檔案物件的 Python 2 C API 的最小模擬 (minimal emulation),它過去依賴於 C 標準函式庫對於緩衝 I/O (FILE*) 的支援。在 Python 3 中,檔案和串流使用新的 io 模組,它在操作系統的低階無緩衝 I/O 上定義了多個層級。下面描述的函式是這些新 API 的便捷 C 包裝器,主要用於直譯器中的內部錯誤報告;建議第三方程式碼改為存取 io API。
- 
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)¶
- 回傳值:新的參照。 Part of the 穩定 ABI 的一部分.Create a Python file object from the file descriptor of an already opened file fd. The arguments name, encoding, errors and newline can be NULLto use the defaults; buffering can be -1 to use the default. name is ignored and kept for backward compatibility. ReturnNULLon failure. For a more comprehensive description of the arguments, please refer to theio.open()function documentation.警告 由於 Python 串流有自己的緩衝層,將它們與操作系統層級檔案描述器混合使用會產生各種問題(例如資料的排序不符合預期)。 在 3.2 版的變更: 忽略 name 屬性。 
- 
int PyObject_AsFileDescriptor(PyObject *p)¶
-  Part of the 穩定 ABI 的一部分.回傳與 p 關聯的檔案描述器作為 int。如果物件是整數,則回傳其值。如果不是整數,則呼叫物件的 fileno()方法(如果存在);該方法必須回傳一個整數,它作為檔案描述器值回傳。設定例外並在失敗時回傳-1。
- 
PyObject *PyFile_GetLine(PyObject *p, int n)¶
- 回傳值:新的參照。 Part of the 穩定 ABI 的一部分.Equivalent to p.readline([n]), this function reads one line from the object p. p may be a file object or any object with areadline()method. If n is0, exactly one line is read, regardless of the length of the line. If n is greater than0, no more than n bytes will be read from the file; a partial line can be returned. In both cases, an empty string is returned if the end of the file is reached immediately. If n is less than0, however, one line is read regardless of length, butEOFErroris raised if the end of the file is reached immediately.
- 
int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction handler)¶
- 覆蓋 - io.open_code()的正常行為以透過提供的處理程式 (handler) 傳遞其參數。- 處理程式是 PyObject *(*)(PyObject *path, void *userData) 型別的函式,其中 path 保證為 - PyUnicodeObject。- userData 指標被傳遞到掛鉤函式 (hook function) 中。由於可能會從不同的執行環境 (runtime) 呼叫掛鉤函式,因此該指標不應直接指向 Python 狀態。 - 由於此掛鉤函式是在導入期間有意使用的,因此請避免在其執行期間導入新模組,除非它們已知有被凍結或在 - sys.modules中可用。- Once a hook has been set, it cannot be removed or replaced, and later calls to - PyFile_SetOpenCodeHook()will fail. On failure, the function returns -1 and sets an exception if the interpreter has been initialized.- 在 - Py_Initialize()之前呼叫此函式是安全的。- 不帶引數地引發一個稽核事件 (auditing event) - setopencodehook。- 在 3.8 版新加入. 
- 
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)¶
-  Part of the 穩定 ABI 的一部分.將物件 obj 寫入檔案物件 p。 flags 唯一支援的旗標是 Py_PRINT_RAW;如果有給定,則寫入物件的str()而不是repr()。在成功回傳0或在失敗回傳-1;將設定適當的例外。
- 
int PyFile_WriteString(const char *s, PyObject *p)¶
-  Part of the 穩定 ABI 的一部分.寫入字串 s 到 檔案物件 p。當成功時回傳 0,而當失敗時回傳 -1,並會設定合適的例外狀況。