Python3 os.fdopen() Method
Python3 OS File/Directory Methods
Overview
The os.fdopen()
method is used to create a file object from a file descriptor fd
and return this file object.
This method is an alias for the built-in function open()
and can accept the same parameters. The only difference is that the first parameter of fdopen()
must be an integer.
Syntax
The syntax for the fdopen()
method is as follows:
os.fdopen(fd, [, mode[, bufsize]]);
Parameters
-
fd -- The file descriptor of the opened file. On Unix, the descriptor is a small integer.
-
mode -- Optional. Similar to Python's built-in open
function, the mode
parameter can specify 'r', 'w', 'a', 'r+', 'w+', 'a+', 'b', etc., indicating whether the file is read-only or writable, and whether the file is opened in binary or text mode. These parameters are similar to the mode
parameter specified in the fopen
function in C language's <stdio.h>
.
-
bufsize -- Optional. Specifies whether the returned file object is buffered: bufsize=0
means no buffering; bufsize=1
means the file object is line-buffered; bufsize=positive number
means using a buffer of the specified size in bytes, but this size is not precise; bufsize=negative number
means using a buffer of the default size, which is usually line-buffered for tty character devices and fully buffered for other files. If this parameter is not specified, the system's default buffering setting is used.
Return Value
Returns a file object from the file descriptor.
Example
The following example demonstrates the use of the fdopen()
method:
Example (Python 3.0+)
#!/usr/bin/python3
import os, sys
# Open a file
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT)
# Get the file object
fo = os.fdopen(fd, "w+")
# Get the current position
print("Current I/O pointer position :%d" % fo.tell())
# Write a string
fo.write("Python is a great language.\nYeah its great!!\n")
# Read the content
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print("Read String is : ", str)
# Get the current position
print("Current I/O pointer position :%d" % fo.tell())
# Close the file
os.close(fd)
print("File closed successfully!!")
Executing the above program outputs the following:
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
File closed successfully!!