我已经创建了这个函数,使我能够输入引号和作者,然后将它们腌制成.txt文件。
然而,似乎我可能仅限于在执行“enterquote”功能时我最终覆盖的一行腌制信息。我似乎无法弄清楚如何在文件中放入更多信息。
我怎么能这样做?
def readquote():
f = open("quote.txt","r")
pquote = pickle.load(f)
pauthor = pickle.load(f)
print "%3s\n - %s" % (pquote, pauthor)
def enterquote():
f = open("quote.txt","w")
quote = raw_input("What quote has its place in the quote book? \n to quit press Q\n\n")
if quote != "Q":
pickle.dump(quote, f)
author = raw_input("what author said that? \n to quit press Q \n\n")
pickle.dump(author, f)
if author == "Q":
print "goodbye"
elif quote == "Q":
print "goodbye"
f.close()
我用架子试过这个:
def readquote():
f = shelve.open('quote.txt')
psaying = f[quote["saying"]]
pauthor = f[quote["author"]]
for key in quote :
print "%3s\n - %s" % (psaying, pauthor)
def enterquote2():
f = shelve.open('quote.txt')
quote = {}
quote["saying"] = raw_input("What quote has its place in the quote book? \n to quit press Q\n\n")
if quote != "Q":
f['saying'] = saying
quote[author] = raw_input("what author said that? \n to quit press Q \n\n")
f['author'] = author
if author == "Q":
print "goodbye"
elif saying == "Q":
print "goodbye"
f.close()
但它给了我一个关于“psaying = f [quote [”说“]]”
的错误我想使用dictionnary格式将say和author结合起来,以便我可以一个接一个地搁置它们,但它让我感到困惑。
答案 0 :(得分:0)
酸洗是针对单个物体的。如果要持久保存多个对象,请使用shelve
模块。它将为您提供一个键值存储。
例如,您可以将enterquote
更改为以下内容:
def enterquote():
f = shelve.open('quote')
quote = raw_input("What quote has its place in the quote book? \n to quit press Q\n\n")
if quote != "Q":
f['quote'] = quote
author = raw_input("what author said that? \n to quit press Q \n\n")
f['author'] = author
if author == "Q":
print "goodbye"
elif quote == "Q":
print "goodbye"
f.close()
您还需要以类似的方式修改readquote
功能。