You are here : python_2ososdup2

os.dup2() - os


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

  • fd -- This is File descriptor to be duplicated.

  • fd2 -- This is Duplicate file descriptor.


os.dup2(fd, fd2);



import os, sys

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

# Write one string
os.write(fd, "This is test")

# 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)
str =, 100)
print "Read String is : ", str

# Close opened file
os.close( fd )

print "Closed the file successfully!!"

Output / Return Value

When we run above program, it produces following result:

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


Alternatives / See Also