
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
- Python Useful Resources
- Python - Questions and Answers
- Python - Quick Guide
- Python - Tools/Utilities
- Python - Useful Resources
- Python - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python os.dup2() Method
Description
Python 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.
Syntax
Following is the syntax for dup2() method −
os.dup2(fd, fd2);
Parameters
fd − This is File descriptor to be duplicated.
fd2 − This is Duplicate file descriptor.
Return Value
This method returns a duplicate of file descriptor.
Example
The following example shows the usage of dup2() method.
#!/usr/bin/python import os, sys # Open a file fd = os.open( "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 = os.read(fd2, 100) print "Read String is : ", str # Close opened file os.close( fd ) print "Closed the file successfully!!"
When we run above program, it produces following result −
Read String is : This is test Closed the file successfully!!
python_files_io.htm
Advertisements