os.fdopen(fd[, mode[, bufsize]])
描述 (Description)
方法fdopen()返回连接到文件描述符fd的打开文件对象。 然后,您可以在文件对象上执行所有已定义的函数。
语法 (Syntax)
以下是fdopen()方法的语法 -os.fdopen(fd, [, mode[, bufsize]]);
参数 (Parameters)fd - 这是要返回文件对象的文件描述符。
mode - 此可选参数是一个字符串,指示如何打开文件。 最常用的模式值是'r'用于读取,'w'用于写入(截断文件,如果它已经存在),和'a'用于追加。
bufsize - 此可选参数指定文件所需的缓冲区大小:0表示无缓冲,1表示行缓冲,任何其他正值表示使用(大约)该大小的缓冲区。
返回值 (Return Value)
此方法返回连接到文件描述符的打开文件对象。
例子 (Example)
以下示例显示了fdopen()方法的用法。#!/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 : This is testPython is a great language.
Yeah its great!!
Current I/O pointer position :45
Closed the file successfully!!