Python os.fdopen() Method
os.fdopen() Overview
The os.fdopen() method is used to create a file object from the file descriptor fd and return that file object.
This method is an alias for the built-in function open() and can take the same arguments, the only difference being that the first argument to fdopen() must be an integer.
os.fdopen() Syntax
The syntax format of the fdopen() method is as follows:
os.fdopen(fd, [, mode[, bufsize]]);
os.fdopen() Parameters
- fd – the descriptor of the open file, under Unix the descriptor is a small integer.
- mode – Optional, like Python’s built-in open function, the mode argument can specify ‘r,w,a,r+,w+,a+,b’, etc., indicating whether the file is read-only or read-write, and whether the file is opened in binary or text form. These parameters are similar to the mode parameters specified in the fopen function in
<stdio.h>
in C language. - bufsize – Optional, specifies whether the returned file object is buffered or not:
- bufsize=0, means it is not buffered;
- bufsize=1, means the file object is line buffered; bufsize=positive, means a buffer flush of the specified size in byte is used, but this size is not exact;
- bufsize=negative. indicates the use of a system default size buffer, which is generally line buffered for tty character devices, and fully buffered for other files.
- If this parameter is not specified, the system default buffering setting is used.
os.fdopen() Return Value
The file object returned by the file descriptor.
os.fdopen() Demo
The following example demonstrates the use of the fdopen() method:
#!/usr/bin/python3
import os, sys
# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Get the object of the above file
fo = os.fdopen(fd, "w+")
# Get current position
print ("Current I/O pointer position :%d" % fo.tell())
# Writing strings
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 position
print ("Current I/O pointer position :%d" % fo.tell())
# Close file
os.close( fd )
print ("Close file successfully!!!")
The output of executing 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
Close file successfully!!!