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

Python3 os.fdopen() Method

Python3 os.fdopen() Method

Python3 OS File/Directory Methods Python3 OS File/Directory Methods


Overview

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

This method is an alias of the built-in function open() and accepts the same arguments; the only difference is that the first argument of fdopen() must be an integer.

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:

Example (Python 3.0+)

#!/usr/bin/python3

import

os

,

sys

Opening a File

fd

=

os

.

open

(

"

foo.txt

"

,

os

.

O_RDWR

|

os

.

O_CREAT

)

Get the object of the above file

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.

\n

Yeah 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

(

)

)

Closing a 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 File/Directory Methods Python3 OS File/Directory Methods