[英]How would you save user data in a list after the program closes without a text.file?
我需要帮助在程序关闭后将用户输入保存到列表而不使用.text文件(如果可能)
我有它,因为我们说Test_Password = [“”]我定义了列表,但每次程序打开时我都必须将它设置为空字符串,因为如果我不这样做,它将不会被定义。
python
def Test1():
ABC_List = [""] #--i'll have to set the list to a blank string
def Test2() #--Another function to skip past the function that defines the list
user_input = input("Already have a letter: [Y]/[N]: ").upper()
if user_input == ("Y"):
print (" ")
x = input("What is your letter: ")
if x in ABC_List:
print (" ")
print ("Awesome! \n")
Test2()
else:
print ("You do not have a letter, go and add one! \n")
Test2() #-- I have no way of saving the data
elif user_input == ("N"):
print (" ")
x = input("Enter a letter! ")
if x in ABC_List:
print (" ")
print ("Sorry, letter is already in list! \n")
Test2()
else:
x.append(ABC_List)
Test()
print ("")
Test2()
Test2()
Test1()
如果您希望在程序运行完毕后记住某些数据,则需要将其保存在某处 。 某种文本文件是一种选择,但还有许多其他选项 - 数据库,各种云存储事物,许多选项。 但是,这些都比文本文件更有用。
为什么需要数据保存,为什么要反对文本文件? 如果我们知道这些问题的答案,那么提供有用的建议会更容易。
更新 :
由于这是一个家庭作业问题,我会给你一些提示,而不是为你做所有的工作。 :-)
正如您已经告诉我们的那样,您只需要输入脚本,因此脚本启动时可能会有也可能没有数据文件。 您可以尝试读取该文件,并处理该文件可能不存在的事实。 在Python中,我们通过捕获异常来处理这类问题。
尝试从文件加载列表,但如果文件不存在则回退到空列表可能看起来像:
try:
with open('abc_list.txt') as abc_list_file:
abc_list = [value.strip() for value in abc_list_file]
except IOError:
abc_list = []
您可以在程序中添加此列表。 当您有要保存的列表时,请执行以下操作:
with open('abc_list.txt', 'w') as abc_list_file:
abc_list_file.writelines(abc_list)
如果不执行IO(输入/输出),则无法保存状态。 如果您无法保存到本地文件,则唯一的选择是IO到另一台计算机(也就是说:通过Internet发送数据)。
否则,要从文件中恢复状态:
file = open('my_things.txt')
# strip() is needed because each line includes a newline character
# at the end
my_things = set(line.strip() for line in file)
file.close()
验证项目是否在此集合中:
if "something" in my_things:
print("I found it!")
else:
print("No such thing!")
在您的集合中添加内容:
my_things.add('something')
将项目写回您的文件:
file = open('my_things.txt', 'w')
for item in my_things:
file.write(item + '\n')
file.close()
合并文件操作:
with open('my_things') as file:
my_things = set(line for line in file)
with open('my_things.txt', 'w') as file:
file.write(item + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.