欢迎访问宙启技术站
智能推送

使用Python编写get_text_list()函数来获取文本列表

发布时间:2023-12-11 07:39:52

下面是一个使用Python编写的get_text_list()函数,用于获取文本列表:

def get_text_list(filename):
    # 打开文件
    try:
        file = open(filename, 'r')
    except FileNotFoundError:
        return ["File not found"]

    # 读取文件内容,将每行文本添加到列表中
    text_list = []
    for line in file:
        text_list.append(line.strip())

    # 关闭文件
    file.close()

    # 返回文本列表
    return text_list

使用例子:

假设有一个文本文件data.txt,包含以下内容:

Hello
World
Python

可以使用以下代码调用get_text_list()函数来获取文本列表:

filename = 'data.txt'
text_list = get_text_list(filename)
print(text_list)

输出结果:

['Hello', 'World', 'Python']

这样,get_text_list()函数会返回包含文件中每行内容的列表。如果指定的文件不存在,则返回一个包含 "File not found" 的列表。