语法
以下是 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!!