簡體   English   中英

在沒有text.file的程序關閉后,如何在列表中保存用戶數據?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM