os.dup() 方法



描述

dup() 方法返回檔案描述符 fd 的副本,可以替代原始描述符使用。

語法

以下是 dup() 方法的語法:

os.dup(fd)

引數

  • fd − 這是原始的檔案描述符。

返回值

此方法返回檔案描述符的副本。

示例

以下示例演示了 dup() 方法的使用:

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 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!!")

執行上述程式後,會產生以下結果:

Closed all the files successfully!
python_os_file_directory_methods.htm
廣告