Python os.fdopen() method
Python OS file/directory methods
Overview
The os.fdopen() method creates a file object from a file descriptor fd and returns that file object.
Available on Unix and Windows.
Syntax
The **fdopen()** method syntax is as follows:
os.fdopen(fd, [, mode[, bufsize]]);
Parameters
-
fd -- The descriptor of the opened file; on Unix a descriptor is a small integer.
-
mode -- Optional. Like the bufsize parameter and Python's built-in open function, the mode parameter can be specified as 'r, w, a, r+, w+, a+, b', etc., indicating whether the file is read-only or readable/writable, and whether it is opened in binary or text form. These parameters are the same as those in the C language's
fopen function's mode parameter in C. -
bufsize -- Optional, specifies whether the returned file object is buffered: bufsize=0 means unbuffered; bufsize=1 means line buffered; a positive bufsize means a buffer of that size in bytes, though the size is not exact; a negative bufsize means a system-default sized buffer, usually line buffered for tty character devices and fully buffered for other files. If this parameter is not specified, the system default buffering is used.
Return Value
The file object returned through the file descriptor.
Example
The following example demonstrates the use of the fdopen() method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys
# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Get the object of the above files
fo = os.fdopen(fd, "w+")
# Get current article
print "Current I/O pointer position :%d" % fo.tell()
# Write string
fo.write( "Python is a great language.\nYeah its great!!\n");
# Read content
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print "Read String is : ", str
# Get current location
print "Current I/O pointer position :%d" % fo.tell()
# Close file
os.close( fd )
print "关闭文件成功!!"
The output of the above program is:
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
关闭文件成功!!