所以我有代码:
def logdata(x, y):
try:
f = open('multlog.txt', 'a')
f.write("{0:g} * {1:g} = {2:g}\n".format(x,y, (x*y)))
except ValueError:
f.write("Error, you tried to multiply by something that wasn't a number")
raise
finally:
f.close()
print("This is a test program, it logs data in a text file, 'multlog.txt'")
fn = input("Enter the first number you'd like to multiply by: ")
sn = input("Enter the second number you'd like to multiply by: ")
logdata(int(fn), int(sn))
我想要它做的是,当它达到值错误时,它写入文件,“错误,你试图乘以不是数字的东西”。但是,如果文件达到值错误,如果用户输入一个字母,比如“j”,ValueError: invalid literal for int() with base 10: 'j'
,它就不会写入文件!
答案 0 :(得分:2)
至少有两个问题:
except
块中写入(或附加)。int()
我会改写为类似下面的例子。
如果您使用with
语句,则可以不使用finally
块。
def logdata(x, y):
with open('multlog.txt', 'a') as f:
try:
x = int(x); y = int(y)
f.write("{0:g} * {1:g} = {2:g}\n".format(x,y, (x*y)))
except ValueError:
f.write("Error")
print("This is a test program, it logs data in a text file, 'multlog.txt'")
fn = input("Enter the first number you'd like to multiply by: ")
sn = input("Enter the second number you'd like to multiply by: ")
logdata(fn, sn)