Python3 Os Fdopen
# Python3.x 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 returns 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. Under 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 read-write, 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's ``.
* **bufsize** -- Optional. Specifies whether the returned file object is buffered: `bufsize=0` means unbuffered; `bufsize=1` means the file object is line-buffered; `bufsize` is a positive integer, indicating the use of a buffer of a specified size in bytes, but this size is not exact; `bufsize` is a negative integer, indicating the use of a system default buffer size. For TTY character devices, this is usually line-buffered, while for other files, it is usually fully buffered. If this parameter is not specified, the system default buffer setting is used.
### Return Value
The file object returned via 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 file fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT)# Get the file object fo = os.fdopen(fd, "w+")# Get current position print("Current I/O pointer position :%d" % fo.tell())# Write string fo.write("Python is a great language.n Yeah 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("File closed successfully!!")
Executing the above program outputs the following:
Current I/O pointer position :0Read String is : This is testPython is a great language.Yeah its great!!Current I/O pointer position :45File closed successfully!!
[ Python3 OS File/Directory Methods](#)
YouTip