Python在同一文件上交错打开/关闭/读/写时会产生IO错误

时间:2009-05-16 15:53:13

标签: python python-3.x

我正在学习Python - 这给了我一个IO错误 -

f = open('money.txt')
while True:
    currentmoney = float(f.readline())
    print(currentmoney, end='')
    if currentmoney >= 0:
        howmuch = (float(input('How much did you put in or take out?:')))

        now = currentmoney + howmuch
        print(now)
        str(now)
        f.close()
    f = open('money.txt', 'w')
    f.write(str(now))
    f.close()

谢谢!

5 个答案:

答案 0 :(得分:3)

while True将永远循环,除非你用break打破它。

I / O错误可能是因为当你完成循环时,你做的最后一件事是f.close(),这会关闭文件。当行currentmoney = float(f.readline())中的循环继续执行时:f将是一个您无法读取的已关闭文件句柄。

答案 1 :(得分:2)

以及几件事......

在临时循环之外

open(money.txt)但是在第一次迭代后关闭它... (技术上你关闭,重新打开并再次关闭)

当循环第二次出现时,f将关闭,f.readLine()很可能会失败

答案 2 :(得分:0)

仅在满足IF条件时关闭文件,否则尝试在IF块之后重新打开它。根据您想要实现的结果,您需要删除f.close调用,或者添加ELSE分支并删除第二个f.open调用。无论如何,让我警告你,IF块中的str(现在)已被弃用,因为你没有在任何地方保存该调用的结果。

答案 3 :(得分:0)

如果money.txt不存在,您的第一行会出现IO错误。

答案 4 :(得分:0)

我可以背驮一个问题吗?以下令我困惑了一段时间。我总是从这些'open()'语句中得到一个IOError,所以我已经停止检查错误了。 (不喜欢这样做!)我的代码出了什么问题?注释中显示的'if IOError:'测试最初位于带有'open()'的语句之后。

if __name__ == '__main__':
#get name of input file and open() infobj
    infname = sys.argv[1]
    print 'infname is:  %s' % (sys.argv[1])
    infobj = open( infname, 'rU' )
    print 'infobj is:  %s' % infobj
# 'if IOError:' always evals to True!?!
#   if IOError:
#       print 'IOError opening file tmp with mode rU.'
#       sys.exit( 1)

#get name of output file and open() outfobj
    outfname = sys.argv[2]
    print 'outfname is: %s' % (sys.argv[2])
    outfobj = open( outfname, 'w' )
    print 'outfobj is: %s' % outfobj
#   if IOError:
#       print 'IOError opening file otmp with mode w.'
#       sys.exit( 2)
相关问题