为什么不写入文件?

时间:2012-03-12 04:22:04

标签: python-3.x

所以我有代码:

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',它就不会写入文件!

1 个答案:

答案 0 :(得分:2)

至少有两个问题:

  1. 该文件未在except块中写入(或附加)。
  2. 正如@DSM在评论中指出的那样,当您致电int()
  3. 时,会引发ValueError

    我会改写为类似下面的例子。
    如果您使用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)
    
相关问题