python-3.x - 如果文件创建了所有数字,如何退出程序
问题描述
我有一个空白文本文件,我需要在其中输入 4 位 message_code 以及最后从 0-9/AZ 的单个数字。所以我可以为每个 message_code 拥有 36 个独特的组合。
我的代码将在 4 位 message_code 的末尾一个一个地写入这个随机数字,但是当所有 36 个组合都用完时,循环不会中断,它会进入无限模式。我想退出程序并向最终用户发送一些消息以输入除 0-9 或 AZ 之外的其他字符。
代码片段:
import random
import string
def checkInput(prompt):
while True:
try:
a = input(prompt)
except ValueError:
print ("Sorry, I didn't understand that")
continue
if not a.strip():
print ("Whitespaces encountered, please enter proper value.")
continue
else:
break
return a
def addnew():
count=int(input("How many new messagecode you want to create? "))
for m in range(0,count):
Mesgcode = checkInput("Enter the mesgcode")
Rkey = random.choice(string.ascii_uppercase+string.digits)
HCode = Mesgcode+Rkey
with open('Host.txt') as f:
z=f.read()
def new():
Rkey = random.choice(string.ascii_uppercase+string.digits)
HCode=Mesgcode+Rkey
return HCode
while HCode in z:
HCode = new()
f1=open('Host.txt', "a")
f1.write("New code added %s\r\n" % HCode)
f1.close()
m+=1
addnew()
Host.txt 文件将如下所示:
ABCD0
ABCD1
ABCD2
.
.
.
ABCD9
ABCDA
.
.
.
ABCDZ
当所有随机数字都用完后,用户应该会收到一条打印的消息Please use different character except 0-9/A-Z, all usage exhausted
,并且程序应该优雅地退出。
解决方案
我认为您可以使用list
或dictionary
保存可能的值。获取值时,将其从您的list
or中删除dictionary
。list
如果或dictionary
为空,请退出此程序。
此外:最好with open
在循环外使用,否则每次进入循环时文件都会打开和关闭。
推荐阅读
- biztalk - BizTalk 部署框架解决方案部署重新启动所有主机实例
- python - 用零填充不均匀点列表的缺失值
- ffmpeg - 使用 ffmpeg 将屏幕和麦克风直播到 azure 媒体服务
- angular - 值(绑定)更改时如何关闭 mat-sidenav?
- linux - 如何更正从 Unix Bourne Shell 的目录中打印出复制的文件?
- java - 通过spring jpa hibernate使用查询时无法findById
- date - 在dataweave中减去两个日期时如何计算年龄?
- javascript - Сonflict onBlur 事件与其他元素上的事件
- mongodb - 带有spring boot的AWS DocumentDB失败错误:com.mongodb.client.internal.MongoClientDelegate没有选择服务器
- grails - Grails 高内存使用 Process.waitForProcessOutput