Python OS file/directory os.dup() method
Python OS File/Directory os.dup() Method
Description
The dup() method returns a copy of the file descriptor fd, which can be used instead of the original descriptor.
Syntax
The syntax of the dup() method is as follows:
os.dup(fd)
Parameters
- fd – This is the original file descriptor.
Return Value
This method returns a copy of the file descriptor.
Example
The following example shows the usage of the dup() method:
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR | os.O_CREAT )
# Get one duplicate file descriptor
d_fd = os.dup( fd )
# Write one string using duplicate fd
line="this is test"
# string needs to be converted to a byte object
b=str.encode(line)
os.write(d_fd, b)
# Close a single opened file
os.closerange( fd, d_fd)
print ("Closed all the files successfully!!")
When we run the above program, it produces the following output:
Closed all the files successfully!