我正在嘗試學習python,並且作爲一個項目我開始製作購物清單文本腳本。該腳本應該問你是否要添加/刪除一個項目到你的列表。它還具有打印列表的功能。您可以將列表保存爲.txt文檔,並在需要時繼續。Python購物清單文本應用程序,保存問題
我的第一個問題是,當我保存列表項並將它們帶回來時,所有不同的列表項已成爲一個列表項。所以我可以補充一下,但我無法從列表中刪除單數項。
我現在試圖從.txt文檔拆分列表。我認爲這會將列表拆分,但現在每次啓動腳本時都會添加額外的符號,然後再次啓動它。我可以做出一些小的調整,還是我的想法里程?
#I think the main problem is in the program_start_list_update_from_file defenition
# Shopping list simulator
shoppingList = []
def program_start_list_update_from_file():
global shoppingList
outputname = "shoppinglistfile.txt"
myfile = open(outputname, 'r')
lines = str(myfile.read().split(', '))
shoppingList = [lines]
myfile.close()
def shopping_list_sim():
print("Would you like to add (a) delete (d) or list (l) items in your shopping list?")
print('Press (e) for exit and (s) for list saving')
playerInput = input()
outputname = "shoppinglistfile.txt"
try:
if playerInput == "a":
print("What item would you like to add?")
shoppingList.append(input())
print("Item added")
shopping_list_sim()
elif playerInput == "d":
print("What item would you like to remove?")
print(shoppingList)
shoppingList.remove(input())
print("Item removed")
shopping_list_sim()
elif playerInput == "l":
myfile = open(outputname, 'r')
yourResult = ', '.join(myfile)
print(yourResult)
shopping_list_sim()
elif playerInput == "e":
print("Exiting program")
sys.exit()
elif playerInput == "s":
myfile = open(outputname, 'w')
myfile.write(', '.join(shoppingList))
myfile.close()
shopping_list_sim()
else:
print("Please use the valid key")
shopping_list_sim()
except ValueError:
print("Please put in a valid list item")
shopping_list_sim()
program_start_list_update_from_file()
shopping_list_sim()
你能否提供一些輸出示例和已保存列表的示例? – TemporalWolf
是的,加了鑰匙,香蕉和胡蘿蔔。首先保存.txt文件後是[''],鍵,香蕉,胡蘿蔔。第二次打開程序並添加鼠標並在此保存之後。結果:[「['']」,'鑰匙','香蕉','胡蘿蔔'],鼠標。第三次添加單詞實例並保存。結果:['['[''''',''''','''','''',''''),'mouse'],實例。 @TemporalWolf –