Python os.fdopen() 方法
概述
os.fdopen() 方法用於通過檔描述符 fd 創建一個檔對象,並返回這個檔對象。
Unix, Windows上可用。
語法
fdopen()方法語法格式如下:
os.fdopen(fd, [, mode[, bufsize]]);
參數
fd -- 打開的檔的描述符,在Unix下,描述符是一個小整數。
mode -- 可選,和bufsize參數和Python內建的open函數一樣,mode參數可以指定『r,w,a,r+,w+,a+,b』等,表示檔的是只讀的還是可以讀寫的,以及打開檔是以二進位還是文本形式打開。這些參數和C語言中的<stdio.h>中fopen函數中指定的mode參數類似。
bufsize -- 可選,指定返回的檔對象是否帶緩衝:bufsize=0,表示沒有帶緩衝;bufsize=1,表示該檔對象是行緩衝的;bufsize=正數,表示使用一個指定大小的緩衝沖,單位為byte,但是這個大小不是精確的;bufsize=負數,表示使用一個系統默認大小的緩衝,對於tty字元設備一般是行緩衝,而對於其他檔則一般是全緩衝。如果這個參數沒有制定,則使用系統默認的緩衝設定。
返回值
通過檔描述符返回的檔對象。
實例
以下實例演示了 fdopen() 方法的使用:
#!/usr/bin/python # -*- coding: UTF-8 -*- import os, sys # 打開檔 fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # 獲取以上檔的對象 fo = os.fdopen(fd, "w+") # 獲取當前文章 print "Current I/O pointer position :%d" % fo.tell() # 寫入字串 fo.write( "Python is a great language.\nYeah its great!!\n"); # 讀取內容 os.lseek(fd, 0, 0) str = os.read(fd, 100) print "Read String is : ", str # 獲取當前位置 print "Current I/O pointer position :%d" % fo.tell() # 關閉檔 os.close( fd ) print "關閉檔成功!!"
執行以上程式輸出結果為:
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 關閉檔成功!!