Python File fileno() 方法返回打开的文件的描述符(或文件句柄)。文件描述符是操作系统用来标识 os 内核中打开的文件的无符号整数。它只保存非负值。
文件描述符的作用就像用于获取存储在数据库中的记录的 ID 一样。因此,Python 使用它对文件执行各种操作;就像打开文件、写入文件、从文件中读取或关闭文件等。
语法
以下是 Python 文件 fileno() 方法的语法 -
fileObject.fileno();
参数
该方法不接受任何参数。
返回值
此方法返回整数文件描述符。
例以下示例显示了 Python File fileno() 方法的用法。在这里,我们尝试使用 file 对象在写入 binary(wb) 模式下打开一个 “foo.txt” 文件。然后,在此文件对象上调用 fileno() 方法以检索引用当前文件的文件描述符。
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
fid = fo.fileno()
print("File Descriptor: ", fid)
# Close opened file
fo.close()
当我们运行上述程序时,它会产生以下结果——
Name of the file: foo.txt
File Descriptor: 3
File Descriptor: 3
例
文件描述符还用于关闭它所表示的文件。
在此示例中,我们将导入 os 模块,因为文件描述符通常由操作系统维护。由于我们使用文件对象来引用文件,因此在表示当前文件的文件对象上调用 fileno() 方法以检索其文件描述符。通过将检索到的文件描述符作为参数传递给 os.close() 方法,可以关闭该文件。
import os
# Open a file using a file object 'fo'
fo = open("hi.txt", "w")
fid = fo.fileno()
print("The file descriptor of the given file: ", str(fid))
# Close the opened file
os.close(fid)
如果我们编译并运行上面的程序,结果会产生如下 -
The file descriptor of the given file: 3
例
但是,如果文件不存在并且程序仍然尝试以读取模式打开它,则 fileno() 方法会引发 FileNotFoundError。
fo = open("hi.txt", "r")
# Return the file descriptor
fid = fo.fileno()
# Display the file descriptor
print(fid)
#Close the opened file
fo.close()
编译并运行上面的程序,得到的输出如下 -
Traceback (most recent call last):
File "D:\qikepu\Programs\Python File Programs\filenodemo.py", line 1, in
fo = open("hi.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'hi.txt'