Python os.fdopen()方法

2019-10-16 23:04:25

Python的os.fdatasync()方法返回連線到檔案描述符fd的開啟的檔案物件。 然後可以對檔案物件執行所有定義的函式功能。

語法

以下是fdopen()方法的語法 -

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

引數

  • fd ? 這是要返回檔案物件的檔案描述符。
  • 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!!