简体   繁体   English

在没有初始化的情况下将计数器存储在搁置文件中 - Python

[英]Storing counter in shelve file without initializing - Python

The program generates a variable guest n with n incrementing for each guest. 该程序为每个客户生成一个变量guest n,其中n递增。 I want the program to start at the last guest number whenever it runs. 我希望程序在运行时从最后一个访客号码开始。

I can only get the program to work by initializing shelf_file["count"] , if I don't I get a key error. 我只能通过初始化shelf_file["count"]来使程序工作,如果我没有得到密钥错误。

shelf_file = shelve.open("mydata")

shelf_file["count"] = 0   #I want to get rid of this line

shelf_file["count"] += 1
guest_id = "guest" + str(shelf_file["count"])

Thanks. 谢谢。

Solved with shelf_file.setdefault("count", 1) shelf_file.setdefault("count", 1)

Thanks @Jkdc for pointing me in the right direction. 谢谢@Jkdc指出我正确的方向。

For some reason shelf_file kept storing "None" until I deleted the files in the directory. 出于某种原因,在删除目录中的文件之前, shelf_file一直存储“None”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM