Python3 os.fopen()方法

fopen()方法函數返回連接到檔描述符fd的一個打開的檔對象。然後,您可以執行所有檔對象中定義的函數。

語法

以下是 fopen()函數方法的語法:
os.fdopen(fd, [, mode[, bufsize]]);

參數

  • fd -- 這是要返回的一個檔對象的檔描述符。

  • mode -- 這個可選參數是表示檔是如何被打開的字串。大部分的模式常用的值是“r”表示讀,"w"表示寫入(截斷檔,如果它已經存在),以及"a"表示追加。

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

返回值

此方法返回連接到檔描述符的一個打開的檔對象。

示例

下麵的例子顯示 fopen()方法的使用。
#!/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!!

上一篇: Python3檔方法 下一篇: Python3 os檔目錄的方法