Python os.path.sameopenfile()
Python os.path.sameopenfile() 方法用于检查给定的文件描述符是否指向同一个文件。
文件描述符是一个小整数值,对应于当前进程已打开的文件。
文件描述符表示一种资源,并作为句柄来执行各种较低级的I/O操作,如读、写、发送等。
例如:标准输入通常是值为0的文件描述符,标准输出通常是值为1的文件描述符,标准错误通常是值为2的文件描述符。当前进程打开的其他文件将获得值3、4、5等等。
语法: os.path.sameopenfile(fd1, fd2)
参数:
fd1:文件描述符。
fd2:文件描述符。
返回类型: 此方法返回类bool的布尔值。如果文件描述符fd1和fd2都引用同一个文件,该方法返回True,否则返回false。
示例1
使用os.path.sameopenfile()方法检查给定的文件描述符是否指向相同的文件。
# Python program to explain os.path.sameopenfile() method
# importing os module
import os
# Path
path = "/home / ihritik / Desktop / file1.txt"
# open the file represented by
# the above given path and get
# the file descriptor associated
# with it using os.open() method
fd1 = os.open(path, os.O_RDONLY)
# open the file represented by
# the above given path and get
# the file object corresponding
# to the opened file
# using open() method
File = open(path, mode ='r')
# Get the file descriptor
# associated with the
# file object 'File'
fd2 = File.fileno()
# check whether the file descriptor
# fd1 and fd2 refer to same
# file or not
sameFile = os.path.sameopenfile(fd1, fd2)
# Print the result
print(sameFile)
# Path
path2 = "/home / ihritik / Documents / sample.txt"
# open the file represented by
# the above given path and get
# the file descriptor associated
# with it using os.open() method
fd3 = os.open(path2, os.O_RDONLY)
# check whether the file descriptor
# fd1 and fd3 refer to same
# file or not
sameFile = os.path.sameopenfile(fd1, fd3)
# Print the result
print(sameFile)
# close file descriptors
close(fd1)
close(fd2)
close(fd3)
输出:
True
False