修改保存在.txt文件中的列表

2024-10-17 08:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在.txt文件中有这个表单的列表:student1, 2, 3 | student2, 1, 4 我需要在程序中调用它,将[student3, 3, 5]添加到列表中,然后将它保存回.txt文件中。我这样做了,但我的列表最后看起来是这样的:[[''], ['Student3', '3', '5']]

f = open('classe1.txt','r')
liste = f.read()
liste = liste.split('|')
n = len(liste)
for i in range (n):
    liste[i] = liste[i].split(',')
liste.append(['Student3','3','5'])
liste = str(liste)

f = open('classe1.txt','w')
f.write(liste)

你会怎么做? 谢谢你


Tags: 文件程序txt表单列表readlenopen
1条回答
网友
1楼 · 发布于 2024-10-17 08:30:46

我不完全确定我是否正确理解了您的问题,但是要将字符串附加到文本文件中,您可以使用a,即:

with open("classe1.txt", "a") as myfile:
    myfile.write("| student3, 3, 5 ")

如果需要将python object写入文件,可以使用json load and dumpPickle

相关问题 更多 >