当我运行程序时如何存储信息

2024-04-27 02:54:31 发布

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

当我运行python时,如何在python中存储信息?在

代码如下:

list = [""]
plist = raw_input("What do you want to append: ")
list.append(plist)
print list

运行时:

^{pr2}$

现在假设我离开去吃饭,然后我回来,我运行程序:

What do you want to append: People
People

问题是程序没有存储Hello这个词,而是保留了一些人。如何让python存储我在原始输入中写入的所有信息?在


Tags: to代码程序you信息inputrawpeople
2条回答

当您重新启动程序时,上一个程序中的所有变量都会被Python转储或“忘记”。如果你想让程序一直询问你想附加什么单词直到你退出,你可以使用for循环或while循环。例如,你可以写下:

for i in range(10):
     plist = raw_input("What do you want to append: ")
     list.append(plist)
     print(list)

这将允许您输入10个单词,list将包含所有这些单词。但是,如果您想关闭程序并重新启动它,并获得上次运行时的所有数据,则应该将其写入外部文件,正如其他人所回答的那样!在

要使信息在执行过程中持久化,应将其保存到文件中。这是编程语言的标准—变量存储在内存(RAM)中,并在每次执行时重置。在

除此之外,在您的示例中,您显式地创建了一个空列表以附加到。若要附加到先前创建的列表,请将该列表保存到一个文件中,然后根据该文件的内容生成该列表。在

# This opens the file and reads each line into the list, then closes it
file=open('listfile.txt','r')
list = file.readlines()
file.close()

plist = raw_input("What do you want to append: ")
list.append(plist)

# This opens the file, writes each item in the list to a line and then closes it    
file=open('listfile.txt','w')
for item in list:
    file.write(str(item))
file.close()

print (list)

相关问题 更多 >