Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python os.fdopen() method

Python os.fdopen() method

Python File methods Python OS file/directory methods


Overview

The os.fdopen() method creates a file object from a file descriptor fd and returns that file object.

Available on Unix and Windows.

Syntax

The **fdopen()** method syntax is as follows:


os.fdopen(fd, [, mode[, bufsize]]);

Parameters

Return Value

The file object returned through the file descriptor.

Example

The following example demonstrates the use of the fdopen() method:


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

import os, sys

# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Get the object of the above files
fo = os.fdopen(fd, "w+")

# Get current article
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 location
print "Current I/O pointer position :%d" % fo.tell()

# Close file
os.close( fd )

print "关闭文件成功!!"

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

Python File methods Python OS file/directory methods