os.fdopen() 方法



描述

方法 `fdopen()` 返回一個連線到檔案描述符 `fd` 的開啟檔案物件。然後,您可以對檔案物件執行所有定義的函式。

語法

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

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

引數

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

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

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

返回值

此方法返回一個連線到檔案描述符的開啟檔案物件。

示例

以下示例演示了 `fdopen()` 方法的用法。

#!/usr/bin/python3
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 : This is testPython is a great language.
Yeah its great!!

Current I/O pointer position :45
Closed the file successfully!!
python_os_file_directory_methods.htm
廣告