美文网首页
Python中List的存储和读取

Python中List的存储和读取

作者: 旅行小张 | 来源:发表于2020-06-24 15:29 被阅读0次

List的存储,存储为txt类型

    # 保存问题列表
    file = open('D:/Python/Projects/NLP/doc2bow/document_questions_list.txt', 'w')
    for fp in document:
        file.write(str(fp))
        file.write('\n')
    file.close()
    print('保存问题文档成功!')

List的读取,读取txt类型文件

    file = open('D:/Python/Projects/NLP/doc2bow/document_questions_list.txt', 'r')
    # 第一种方法,直接用read()读取,然后用splitlines()分行
    # 优点是简单不用写循环,缺点是读取的数据很大时可能会出现错误
    # document_load = file.read().splitlines()
    # 第二种方法,使用readlines()读取,遍历每一行,去除每一行末尾的换行符后,添加到List中
    document_load = []
    for line in file.readlines():
        line = line.strip('\n')
        document_load.append(line)
    file.close()
    print('读取文档成功!')

完成!

相关文章

网友评论

      本文标题:Python中List的存储和读取

      本文链接:https://www.haomeiwen.com/subject/pnbrfktx.html