使用Python实现get_text_list()函数以获取文本列表
发布时间:2023-12-11 07:42:40
下面是一个实现get_text_list()函数的Python代码,该函数可以从一个文本文件中读取内容,并将其存储在一个列表中返回:
def get_text_list(filename):
text_list = []
try:
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
text_list.append(line.strip())
except FileNotFoundError:
print(f"Error: {filename} not found.")
return text_list
使用示例:
假设我们有一个名为example.txt的文本文件,内容如下:
Hello, world! This is an example file. We are testing get_text_list() function.
我们可以调用get_text_list()函数来获取文件内容的列表形式:
filename = 'example.txt' text_list = get_text_list(filename) print(text_list)
输出结果:
['Hello, world!', 'This is an example file.', 'We are testing get_text_list() function.']
这样就可以获得文本文件内容的列表形式,可以方便地对每一行进行处理。
