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

Python3 os.dup() Method

Python3 os.dup() Method

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


Overview

The os.dup() method duplicates the file descriptor fd.

Syntax

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


os.dup(fd);

Parameters

Return Value

Returns the duplicated file descriptor.

Example

The following example demonstrates the use of the dup() 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

)

Duplicate the file descriptor

d_fd

=

os

.

dup

(

fd

)

Write to the file using the duplicated file descriptor

os

.

write

(

d_fd

,

"

This is test

"

.

encode

(

)

)

Closing a File

os

.

closerange

(

fd

,

d_fd

)

print

(

"

All files closed successfully!!

"

)

The output of the above program is:

关闭所有文件成功!!

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