Python3 os.fdopen() Method

Python3 OS 文件/目录方法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 a built-in functionopen()alias, and can accept the same parameters. The only difference is that the first parameter of fdopen() must be an integer.

Syntax

fdopen()The method syntax 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. Same as the Python 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 readable/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 <stdio.h> in C language.

  • 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 a buffer of a specified size is used, in bytes, but this size is not precise; bufsize=negative number means a system-default buffer size is used. 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's default buffering settings are used.

Return Value

A 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 of the above file 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.\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 ("File closed successfully!!")

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
关闭文件成功!!

Python3 OS 文件/目录方法Python3 OS File/Directory Methods

Other Extensions