[英]Saving inputs into a list?
I wanted to make a program (or whatever the correct terminology is) where it lets you enter a small greeting that gets stored in a list.我想制作一个程序(或任何正确的术语),让您输入一个存储在列表中的小问候语。
What I can't figure out is how I can make the program save that list either in a separate file, or within the program, so that when I open it and run it again I have access to that same list.我想不通的是如何让程序将该列表保存在单独的文件中或在程序中,以便当我打开它并再次运行它时,我可以访问同一个列表。
This is my function where the user would input their greeting:这是我的 function,用户将在其中输入他们的问候语:
def greetings():
print('Would you like to submit a new greeting?')
yesno() # Ignore this
greeting = input()
storage = []
if len(greeting) < 3:
print("That's too short.")
elif len(greeting) > 15:
print("That's too long.")
elif greeting == 'debug':
print(storage)
else:
storage.append(greeting)
I put that function in:我把 function 放在:
while True:
user = input()
user_length = len(user)
if int(user_length) < 2 or int(user_length) > 15 and tries < 3:
tries = tries + 1
print("Please enter a valid name.")
else:
greetings()
To Store A Input Permanently You Need You Either Store It In A Database or a file in this case i'am storing this in a.txt file要永久存储输入,您需要将其存储在数据库或文件中,在这种情况下,我将其存储在 a.txt 文件中
while True:
text = input("Please Enter Some Random Text Here:\n")
# Make Sure That The File `inputs.txt` exists!
with open('inputs.txt', encoding='utf-8', mode='a') as file: # Mode'a' = append
file.write('\n'+text)
file.close() # To save some memory
This Is Just The 'skeleton' for your question 'What I can't figure out is how I can make the program save that list either in a separate file, or within the program, so that when I open it and run it again I have access to that same list.'这只是您问题的“骨架” “我不知道的是如何让程序将该列表保存在单独的文件中或程序中,以便当我打开它并再次运行它时我可以访问同一个列表。
import traceback, ast, random
def greetings():
print('Would you like to submit a new greeting? ')
# yesno() # Ignore this
greeting = input()
if len(greeting) < 3:
print("That's too short.")
elif len(greeting) > 15:
print("That's too long.")
elif greeting == 'debug':
print(storage)
else:
storage = []
try:
previous = open('data.txt', 'r')
read = previous.read()
storage = ast.literal_eval(read)
previous.close()
except:
print(traceback.format_exc())
storage = []
print("File not found")
storage.append(greeting)
write = open('data.txt', 'w')
write.write(str(storage))
write.close()
print("Random greeting - {}".format(random.choice(storage)))
while True:
user = input('Enter your name : ')
user_length = len(user)
if int(user_length) < 2 or int(user_length) > 15 and tries < 3:
tries = tries + 1
print("Please enter a valid name.")
else:
greetings()
This reads the file every time there is a new entry and adds new greeting to the end of the list and writes to file.每次有新条目时都会读取文件,并将新问候语添加到列表末尾并写入文件。 After writing to file, it prints a random greeting from the list
写入文件后,它会从列表中随机打印一条问候语
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.