运行时如何在python中存储信息?
这是代码:
list = [""]
plist = raw_input("What do you want to append: ")
list.append(plist)
print list
Run Code Online (Sandbox Code Playgroud)
当它运行时:
What do you want to append: Hello
Hello
Run Code Online (Sandbox Code Playgroud)
现在让我们说我离开去吃饭然后回来,我运行程序:
What do you want to append: People
People
Run Code Online (Sandbox Code Playgroud)
问题是该程序没有存储Hello这个词并保留了People.如何让python存储我在raw_input存储中写的所有信息呢?
要使信息在执行过程中保持不变,您应该将其保存到文件中.这是编程语言的标准 - 变量存储在内存(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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1127 次 |
| 最近记录: |