在Python程序中读写文本文件

在本教程中,我们将学习Python中的文件处理。我们可以使用内置函数轻松地在Python中编辑文件。

我们有两种可以在Python中编辑的文件。让我们看看它们是什么。

文字档案

文本文件是包含英文字母的普通文件。我们称这些文件中的内容为文本。

二进制文件

二进制文件包含0和1的数据。我们无法理解该语言。

文件访问方式

每当我们使用Python处理文件时,都必须提及文件的访问方式。例如,如果您要打开文件以在其中写入内容,则它是一种模式。同样,我们有不同的访问模式。

只读-r

在这种模式下,我们只能读取文件的内容。如果该文件不存在,那么我们将收到错误消息。

读写-r +

在这种模式下,我们可以读取文件的内容,也可以将数据写入文件。如果该文件不存在,那么我们将收到错误消息。

只写-w

在这种模式下,我们可以将内容写入文件。文件中存在的数据将被覆盖。如果该文件不存在,那么它将创建一个新文件。

仅追加-a

在这种模式下,我们可以在最后添加数据到文件中。如果该文件不存在,那么它将创建一个新文件。

追加并写入-a +

在这种模式下,我们可以将数据追加并写入文件。如果该文件不存在,那么它将创建一个新文件。

写入文件

让我们看看如何将数据写入文件。

  • w模式下使用open()打开文件。如果必须使用文件读取和写入数据,请在r +模式下将其打开。

  • 使用write()writelines()方法将数据写入文件

  • 关闭文件。

我们有以下代码可以实现我们的目标。

示例

# opening a file in 'w'
file = open('sample.txt', 'w')
# write() - it used to write direct text to the file
# writelines() - it used to write multiple lines or strings at a time, it takes ite
rator as an argument
# writing data using the write() method
file.write("I am a Python programmer.\nI am happy.")
# closing the file
file.close()

进入程序目录,您将找到一个名为sample.txt的文件。查看其中的内容。

从文件读取

我们已经看到了一种将数据写入文件的方法。让我们研究一下如何读取已写入文件的数据。

  • r模式下使用open()打开文件。如果必须使用文件读取和写入数据,请在r +模式下将其打开。

  • 使用read()或readline()readlines()方法从文件中读取数据。将数据存储在变量中。

  • 显示数据。

  • 关闭文件。

我们有以下代码可以实现我们的目标。

示例

# opening a file in 'r'
file = open('sample.txt', 'r')
# read() - it used to all content from a file
# readline() - it used to read number of lines we want, it takes one argument which
is number of lines
# readlines() - it used to read all the lines from a file, it returns a list
# reading data from the file using read() method
data = file.read()
# printing the data
print(data)
# closing the file
file.close()

输出结果

如果运行上面的程序,您将得到以下结果。

I am a Python programmer.
I am happy.

结论

希望您能理解本教程。如果您有任何疑问,请在评论部分中提及。