Python os.fdopen() 方法



Python OS 模組的fdopen() 方法接受檔案描述符作為引數值,並返回相應的 file 物件。這允許我們執行所有已定義的操作,例如讀取和寫入給定的 file 物件。

術語檔案描述符可以定義為一個整數值,它從核心為每個程序維護的一組開啟檔案中標識開啟的檔案。

語法

以下是 Python fdopen() 方法的語法:

os.fdopen(fd, [, mode[, bufsize]]);

引數

Python os.fdopen() 方法接受以下引數:

  • fd - 這是要返回其 file 物件的檔案描述符。

  • mode - 此可選引數是一個字串,指示如何開啟檔案。mode 的最常用值是 'r' 用於讀取,'w' 用於寫入(如果檔案已存在則截斷),'a' 用於追加。

  • bufsize - 此可選引數指定檔案所需的緩衝區大小:0 表示無緩衝,1 表示行緩衝,任何其他正值表示使用(大約)該大小的緩衝區。

返回值

Python os.fdopen() 方法返回連線到檔案描述符的開啟 file 物件。

示例

以下示例顯示了 fdopen() 方法的使用。在這裡,我們以讀寫許可權開啟一個檔案。然後,我們在讀取給定檔案的文字之前和之後檢查 I/O 指標位置。

#!/usr/bin/python
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Now get a file object for the above file.
fo = os.fdopen(fd, "w+")
# Tell the current position
print ("Current I/O pointer position :%d" % fo.tell())
# Write one string
fo.write( "Python is a great language.\nYeah its great!!\n");
# Now read this file from the beginning.
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)
# Tell the current position
print ("Current I/O pointer position :%d" % fo.tell())
# Close opened file
fo.close()
print ("Closed the file successfully!!")

執行上述程式時,將產生以下結果:

Current I/O pointer position :0
Read String is :  b'Python is a great language.\nYeah its great!!\n'

Current I/O pointer position :45
Closed the file successfully!!

示例

要為給定的檔案描述符指定行緩衝區,請將緩衝區大小的值為 1 作為引數傳遞給 fdopen(),如下面的程式碼所示。

import os

# Open a file descriptor
fd = os.open("txtFile.txt", os.O_RDWR|os.O_CREAT)

# file object with 1-byte line buffer
with os.fdopen(fd, 'w+', buffering=1) as file:
   file.write("This is tutorialspoint.")
   file.seek(0)
   print(file.read())

上述程式將顯示以下輸出:

This is tutorialspoint.
python_files_io.htm
廣告