Python 如何在文本文件中写入单行数据
Python内置了文件创建、写入和读取功能。在Python中,可以处理两种类型的文件:文本文件和二进制文件(用二进制语言表示的0和1)。
本文将讲解如何向文件中写入数据。
首先,我们需要使用open()函数以写入模式打开文件。然后,使用write()方法将提供的文本保存到文件中。文件模式和流位置决定了提供的文本将放置在哪里。
- “a” - 文本将放置在文件流的当前位置,通常为文件末尾。
-
“w” - 在插入文本之前,文件将被清空,当前文件流位置默认为0。
语法
下面是open()方法的语法。
file = open("file_name", "access_mode")
示例1
让我们来看一个以写模式打开文件的示例。如果 example.txt 文件不存在, open() 函数会创建一个新文件。
file = open('example.txt', 'w')
输出
执行上述程序后,会生成以下输出结果。
The file example.txt is opened in write mode.
示例2
在以下示例中,使用 open() 方法以写模式打开一个文件。然后,利用 write() 方法将文本写入文件,并使用 close() 方法关闭文件。
#python program to demonstrate file write()
file = open('example.txt', 'w')
file.write( "the end")
file.close()
输出
执行上述程序后,会生成以下输出结果。
The text "the end" is written into the file. The previous contents of the file have been cleared.
从前面的示例中,我们使用写入模式将内容写入文件。要在不清除之前内容的情况下将内容写入文件,我们可以使用附加模式(’a’)。使用附加模式写入文件时,以附加模式打开文件,使用’a’或’a+’作为访问模式,在现有文件末尾添加新行。以下是这些访问模式的定义:仅附加(’a’):要开始写入,请打开文件。如果文件不存在,说明将被创建。文件的句柄位于文件的最末尾。
示例3
在下面的示例中,使用open()函数以附加模式打开名为example.txt的文件。然后,使用write()函数将文本写入文件中。
#python program to demonstrate file write in append mode
file = open('example.txt', 'a')
file.write( "the end ")
输出
在执行以上程序时,将生成以下输出。
The text is appended to the file.
示例4
在下面的示例中,使用 open() 函数以追加模式打开一个文件。然后,使用 write() 函数将文本写入文件,并使用 close() 函数关闭文件。
#python program to demonstrate file write in append mode
f = open('myfile', 'a')
f.write('hi there\n')
# python will convert \n to os.linesep
f.close()
输出
在执行上述程序时,会产生以下输出。
The text is appended in the file in a next line.