【问题标题】:save python list to text for next use将 python 列表保存为文本以供下次使用
【发布时间】:2022-01-18 14:26:46
【问题描述】:

我正在处理这个项目(Link),我想将导出数据保存在 csv 或文本文件中以备下次使用; 保存数据的代码是

with open('listfile.txt', 'w') as filehandle:
    for listitem in record_list:
        filehandle.write('%s\n' % listitem)

加载数据的代码是

# define an empty list
places = []

# open file and read the content in a list
with open('listfile.txt', 'r') as filehandle:
    for line in filehandle:
        # remove linebreak which is the last character of the string
        currentPlace = line[:-1]

        # add item to the list
        places.append(currentP

但正确加载数据时未加载数据

【问题讨论】:

  • “未正确加载”不是错误描述。你怎么知道它没有正确加载?您收到错误消息吗?
  • Welcome to SO ;) 该代码对我来说非常完美 :) 请添加更准确的错误描述
  • 您的代码目前有一些拼写错误:py places.append(currentP python 3.9.7 我本可以通过一些小的修复使其工作,请确保您已将代码完全复制/粘贴到此线程中。

标签: python list csv


【解决方案1】:

实际上,您可以使用 readlines() 将所有数据加载到一个列表中,该列表将每一行都保留为一个元素。

with open('listfile.txt', 'r') as filehandle:
    places = filehandle.readlines() # creating a list which makes each line an element

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多