Easy Tutorial
❮ Python File Writelines Python If Example ❯

Python3 os.dup2() Method

Python3 OS File/Directory Methods


Overview

The os.dup2() method is used to duplicate a file descriptor fd to another fd2.

Available on Unix, Windows.

Syntax

The syntax for the dup2() method is as follows:

os.dup2(fd, fd2);

Parameters

Return Value

No return value.

Example

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

import os

# Open a file
f = open('txt', 'a')

# Duplicate the file descriptor to stdout (file descriptor 1)
os.dup2(f.fileno(), 1)

# Close the file
f.close()

# Print to standard output, which is now the file
print('tutorialpro')
print('google')

Executing the above program will output the following, creating a txt file with the content:

tutorialpro
google

Python3 OS File/Directory Methods

❮ Python File Writelines Python If Example ❯