Python 如何将列表内容写入文件
本文将向您展示如何使用Python将列表中的数据写入文本文件。
假设我们取了一个列表,并将列表中的所有元素写入一个名为” ListDataFile.txt “的文本文件,写入后该文件中的数据如下所示。
假设我们有一个文本文件中有以下列表内容:
inputList = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file']
使用此程序,我们将得到上述字符串的以下结果-
This
is
a
TutorialsPoint
sample
file
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储元素列表。
-
创建一个变量来存储文本文件的路径。
-
使用 open() 函数(它打开一个文件并返回一个文件对象作为结果)以只读模式打开文本文件,将文件名和模式作为参数传递给它(这里的 “w” 表示写模式)。
with open(inputFile, 'w') as filedata:
-
使用for循环遍历输入列表的每个元素。
-
使用write()函数将列表的每个元素(迭代值)写入已打开的文本文件中(write()函数将指定的文本写入文件。提供的文本将根据文件模式和流位置插入)。
-
使用for循环遍历文件中的每一行。
-
使用close()函数关闭输入文件(用于关闭已打开的文件)。
-
使用open()函数以只读模式打开文本文件,将文件名和模式作为参数传递给它(这里“r”表示只读模式)。
with open(inputFile, 'r') as filedata:
- 使用 read() 函数读取文件数据后,打印文本文件的内容(从文件中读取指定数量的字节并返回)。默认值为-1,表示整个文件。
示例
以下程序遍历文本文件的行,并使用collections模块中的counter函数打印文本文件中键值对的频率。
# input list
inputList = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file']
# input text file
inputFile = "ListDataFile.txt"
# Opening the given file in write mode
with open(inputFile, 'w') as filedata:
# Traverse in each element of the input list
for item in inputList:
# Writing each element of the list into the file
# Here “%s\n” % syntax is used to move to the next line after adding an item to the file.
filedata.write("%s\n" % item)
# Closing the input file
filedata.close()
# Opening the output text file in read-only mode
fileData = open("ListDataFile.txt")
# Reading the file and printing the result
print(fileData.read())
输出
在执行上述程序时,将生成以下输出 −
This
is
a
TutorialsPoint
sample
file
我们在这个程序中读取了一个单词列表,然后选择一个文件并以写入模式打开它。然后,使用循环,我们对列表中的每个单词进行遍历,并使用write()函数将该单词添加到文件中。我们使用换行字符(\n)来分隔文件的单词。之后,我们关闭文件并以读取模式重新打开它,打印出文件的所有数据(这里的数据将是列表中的单词)
我们从这篇文章中学习了如何以写入模式打开文件并将数据写入文件,以及如何遍历单词列表并将这些项复制到文件中。如何重新打开文件以读取其内容(这用于检查单词是否已添加到文件中)。
极客笔记