Python3 os.dup()方法

dup()方法返回文件描述符fd,其可以代替原来描述使用。

语法

以下是 dup() 方法的语法:
os.dup(fd)

参数

  • fd -- 这是原始文件描述符

返回值

这个方法返回的文件描述符的副本

示例

下面的示例显示 dup() 方法的用法:
#!/usr/bin/python3

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

上一篇: Python3文件方法 下一篇: Python3 os文件目录的方法