Python open() 函数是一个内置函数,用于打开文件并返回其相应的文件对象。要执行读取和写入等文件操作,您首先需要使用 open() 函数打开文件。如果文件不存在,则 open() 方法返回 “FileNotFoundError” 异常。
文件打开模式
以下是与 open() 函数一起用于打开文件的不同文件打开模式:
- r − 它将以只读模式打开文件。
- w − 当我们想要写入和截断文件时使用它。
- x − 它用于创建文件。如果文件已存在,将引发错误。
- a − 打开一个文件,以便在末尾附加文本。
- b − 它指定二进制模式。
- t − 它指定文本模式。
- +− 打开文件进行更新。
语法
Python open() 函数的语法如下 -
open(file, mode)
参数
Python open() 函数接受两个参数 -
- file − 此参数表示文件的路径或名称。
- mode − 它表示我们要打开文件的模式。
返回值
Python open() 函数返回一个文件对象。
open() 函数示例
练习以下示例来理解 Python 中 open() 函数的用法:
示例:使用 open() 函数在读取模式下打开文件
以下示例演示如何使用 Python open() 函数。在这里,我们将以只读模式打开一个文件并打印其内容。
with open("newFile.txt", "r") as file:
textOfFile = file.read()
print("The file contains the following code:")
print(textOfFile)
当我们运行上述程序时,它会产生以下结果——
The file contains the following code:
Hi! Welcome to qikepu...!!
Hi! Welcome to qikepu...!!
示例:使用 open() 函数以追加模式打开文件
当我们以附加模式打开文件时,用 “a” 表示,该文件允许我们向其附加文本。在下面的代码中,我们将打开一个文件以向其写入文本。
with open("newFile.txt", "a") as file:
file.write("\nThis is a new line...")
file.close()
with open("newFile.txt", "r") as file:
textOfFile = file.read()
print("The file contains the following text:")
print(textOfFile)
以下是上述代码的输出 -
The file contains the following text:
Hi! Welcome to qikepu...!!
This is a new line...
Hi! Welcome to qikepu...!!
This is a new line...
示例:使用 open() 函数以读取模式打开二进制文件
我们还可以读取文件的文本并将其转换为二进制格式。我们需要将此操作的模式指定为 “rb”。下面的代码演示了如何以二进制格式读取给定文件的内容。
fileObj = open("newFile.txt", "rb")
textOfFile = fileObj.read()
print("The binary form of the file text:")
print(textOfFile)
上述代码的输出如下 -
The binary form of the file text:
b'Hi! Welcome to qikepu...!!\r\n\r\nThis is a new line...'
b'Hi! Welcome to qikepu...!!\r\n\r\nThis is a new line...'