Python os.close() 方法关闭指定的文件描述符。Python 中的文件描述符是表示 os 内核中打开文件的标识符,并保存在文件表中。
通常,文件描述符具有非负值。负结果表示错误或“无值”条件。他们协助的主要工作是访问文件和其他输入/输出设备,如网络套接字或管道。
语法
以下是 Python os.close() 方法的语法 -
参数
- fd − 这是文件的文件描述符。
返回值
此方法不返回任何值。
示例 1
以下示例显示了 Python os.close() 方法的用法。在这里,我们将创建一个文件描述符 'os.O_RDWR|os.O_CREAT”。然后我们在文件中写入一个字符串 “This is test”。此后,我们将使用此方法关闭文件。
当我们运行上述程序时,它会产生以下结果——
Closed the file successfully!!
示例 2
在下面给出的示例中,我们将创建一个文件描述符 'r'。这意味着读取文件。
在执行上述代码时,我们得到以下输出 -
The descriptor of the file for code.txt is 3
示例 3
如果文件描述符无效,则此方法将引发 EBADF 错误。
以下是上述代码的输出 -
Traceback (most recent call last):
File "/home/sarika/Desktop/chown.py", line 5, in <module>
os.close(filedesc + 1)
OSError: [Errno 9] Bad file descriptor
File "/home/sarika/Desktop/chown.py", line 5, in <module>
os.close(filedesc + 1)
OSError: [Errno 9] Bad file descriptor