如何将列表保存到文件并以列表类型读取

如何将列表保存到文件并以列表类型读取

本文介绍了如何将列表保存到文件并以列表类型读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的列表得分= [1,2,3,4,5],并且在我的程序运行时它被更改了.如何将其保存到文件中,以便下次运行程序时可以将更改后的列表作为列表类型访问?

Say I have the list score=[1,2,3,4,5] and it gets changed whilst my program is running. How could I save it to a file so that next time the program is run I can access the changed list as a list type?

我尝试过:

score=[1,2,3,4,5]

with open("file.txt", 'w') as f:
    for s in score:
        f.write(str(s) + '\n')

with open("file.txt", 'r') as f:
    score = [line.rstrip('\n') for line in f]


print(score)

但这会导致列表中的元素是字符串而不是整数.

But this results in the elements in the list being strings not integers.

推荐答案

我决定不使用泡菜,因为我希望能够在测试期间打开文本文件并轻松更改其内容.因此,我这样做:

I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:

score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")

with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

因此,尽管文件中的项目以字符串形式存储在文件中,但它们仍被读取为整数.

So the items in the file are read as integers, despite being stored to the file as strings.

这篇关于如何将列表保存到文件并以列表类型读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:29
查看更多