带有一些错误处理的短程序:
创建演示数据文件:
t = """
emailnumberone@gmail.com:password1
emailnumbertwo@gmail.com:password2
emailnumberthree@gmail.com:password3
emailnumberfour@gmail.com:password4
emailnumberfive@gmail.com:password5
k
: """
with open("f.txt","w") as f: f.write(t)
解析数据/存储:
def store_in_db(email,pw):
# replace with db access code
# see http://bobby-tables.com/python
# for parametrized db code in python (or the API of your choice)
print("stored: ", email, pw)
with open("f.txt") as r:
for line in r:
if line.strip(): # weed out empty lines
try:
email, pw = line.split(":",1) # even if : in pw: only split at 1st :
if email.strip() and pw.strip(): # only if both filled
store_in_db(email,pw)
else:
raise ValueError("Something is empty: '"+line+"'")
except Exception as ex:
print("Error: ", line, ex)
输出:
stored: emailnumberone@gmail.com password1
stored: emailnumbertwo@gmail.com password2
stored: emailnumberthree@gmail.com password3
stored: emailnumberfour@gmail.com password4
stored: emailnumberfive@gmail.com password5
Error: k
not enough values to unpack (expected 2, got 1)
Error: : Something is empty: ': '
编辑:根据What characters are allowed in an email address? - 如果引用,':' 可能是电子邮件第一部分的一部分。
理论上这将允许输入为
`"Cool:Emailadress@google.com:coolish_password"`
此代码会出错。请参阅Talip Tolga Sans answer 了解如何以不同方式分解拆分以避免此问题。