Python 运行程序时如何存储信息
运行python时,如何在python中存储信息 代码如下:Python 运行程序时如何存储信息,python,Python,运行python时,如何在python中存储信息 代码如下: list = [""] plist = raw_input("What do you want to append: ") list.append(plist) print list 运行时: What do you want to append: Hello Hello 现在让我们假设我离开去吃饭,然后我回来,我运行程序: What do you want to append: People People 问题是,这个程序没有
list = [""]
plist = raw_input("What do you want to append: ")
list.append(plist)
print list
运行时:
What do you want to append: Hello
Hello
现在让我们假设我离开去吃饭,然后我回来,我运行程序:
What do you want to append: People
People
问题是,这个程序没有存储Hello这个词,并没有让人留下。如何使python存储我在原始输入中写入的所有信息并将其存储?要使信息在执行过程中持久化,应将其保存到文件中。这是编程语言的标准-变量存储在内存(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)
要使信息在执行过程中持久化,应将其保存到文件中。这是编程语言的标准-变量存储在内存(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)
重新启动程序时,Python会转储或“忘记”上一个程序中的所有变量。如果您想让程序在退出之前一直询问要附加的单词,可以使用
for
循环或while
循环。例如,您可以只写:
for i in range(10):
plist = raw_input("What do you want to append: ")
list.append(plist)
print(list)
这将允许您输入10个单词,
list
将包含所有单词。但是,如果您想关闭程序并重新启动它,并且拥有上次运行时的所有数据,那么您应该将其写入外部文件,正如其他人所回答的那样 重新启动程序时,Python会转储或“忘记”上一个程序中的所有变量。如果您想让程序在退出之前一直询问要附加的单词,可以使用for
循环或while
循环。例如,您可以只写:
for i in range(10):
plist = raw_input("What do you want to append: ")
list.append(plist)
print(list)
这将允许您输入10个单词,
list
将包含所有单词。但是,如果您想关闭程序并重新启动它,并且拥有上次运行时的所有数据,那么您应该将其写入外部文件,正如其他人所回答的那样 您需要了解有关文件的信息。您可以将数据写入文件。您可能希望使用流行的json格式。在python中搜索json.dump和文件您需要了解有关文件的信息。您可以将数据写入文件。您可能希望使用流行的json格式。在python中搜索json.dumps和文件“r”和“w”是什么意思?我必须使用file=open(ect)还是可以将名称file改为filename?@Supercolbat可以是任何有效的变量名“r”和“w”是什么意思?我必须使用file=open(ect)吗或者我可以将文件名改为filename吗?@Supercolbat,可以是任何有效的变量名