Python 3 - os.dup2() Method


The method dup2() duplicates file descriptor fd to fd2, closing the latter first if necessary.

Note − New file description would be assigned only when it is available. In the following example given below, 1000 would be assigned as a duplicate fd in case when 1000 is available.


Following is the syntax for dup2() method −

os.dup2(fd, fd2)


  • fd − This is File descriptor to be duplicated.

  • fd2 − This is Duplicate file descriptor.

Return Value

This method returns a duplicate of file descriptor.


The following example shows the usage of dup2() method.

import os, sys

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

# Write one string using duplicate fd
line = "this is test" 

# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)

# Now duplicate this file descriptor as 1000
fd2 = 1000
os.dup2(fd, fd2);

# Now read this file from the beginning using fd2.
os.lseek(fd2, 0, 0)
line =, 100)
str = line.decode()
print ("Read String is : ", str)

# Close opened file
os.closerange( fd,fd2 )

print ("Closed the file successfully!!")


When we run the above program, it produces the following result −

Read String is :  This is test
Closed the file successfully!!