Python os.fdopen() Method

Python File(文件) 方法Python 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.

Available on Unix and Windows.

Syntax

fdopen()The method syntax format 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. Like the bufsize parameter and 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 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 C'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 a specified size in bytes, but this size is not exact; bufsize=negative number means using a system default buffer size. For tty character devices, it 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:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 获取以上文件的对象
fo = os.fdopen(fd, "w+")

# 获取当前文章
print "Current I/O pointer position :%d" % fo.tell()

# 写入字符串
fo.write( "Python is a great language.\nYeah its great!!\n");

# 读取内容
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print "Read String is : ", str

# 获取当前位置
print "Current I/O pointer position :%d" % fo.tell()

# 关闭文件
os.close( fd )

print "关闭文件成功!!"

Executing the above program produces the following output:

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

Python File(文件) 方法Python OS File/Directory Methods

Other Extensions