在程序关闭后,如何在列表中保存用户数据文本文件?

2024-04-26 22:42:59 发布

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

我需要帮助保存用户输入到一个列表后,程序关闭没有一个.text文件(如果可能的话)

我有它,比如说Test\u 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()

Tags: thetoin程序列表inputifhave
2条回答

如果您想在程序运行结束后记住某些数据,则需要将其保存在某处。某种类型的文本文件可能是一种选择,但也有许多其他选择——数据库、各种云存储设备、许多选择。不过,这些都比文本文件要复杂得多。你知道吗

为什么你需要保存数据,为什么你反对一个文本文件?如果我们知道这些问题的答案,就更容易提出有帮助的建议。你知道吗

更新

既然这是一个家庭作业问题,我就给你一些提示,而不是为你做所有的工作。:-)

正如您所说的,您将只提交脚本,因此在脚本启动时可能存在或不存在数据文件。您可以尝试读取文件,并处理文件可能不在那里的事实。在Python中,我们通过catching exceptions处理这类问题。你知道吗

尝试从文件加载列表,但如果该文件不存在,则返回到空列表可能如下所示:

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')

相关问题 更多 >