Python在同一文件上交替打开/关闭/读取/写入时产生IO错误
我正在学习Python,这让我遇到了一个输入输出错误。
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
如果money.txt这个文件不存在,你在第一行代码运行时就会遇到输入输出错误。
2
嗯,有几点需要注意...
你在循环外面用 open(money.txt)
打开了文件,但在第一次循环后就把它关掉了...
(严格来说,你是先关掉,再重新打开,然后再关一次)
当循环第二次运行时,f
会已经被关闭,这时候 f.readLine()
很可能会出错。
3
while True
这个循环会一直转下去,除非你用 break
来打断它。
出现输入输出错误可能是因为你在循环结束时最后做的事情是 f.close()
,这会关闭文件。然后当程序继续执行到 currentmoney = float(f.readline())
这一行时,f
就变成了一个已经关闭的文件句柄,你无法再从中读取数据。