Python 在同一文件上交错打开/关闭/读取行/写入时生成 IO 错误
-
22-08-2019 - |
题
我正在学习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()
谢谢!
解决方案
在while True
将会永远循环下去,除非你有break
打破它。
在I / O错误可能是因为当你运行循环,一旦你做的最后一件事是f.close()
,其中关闭文件。当继续执行在线路currentmoney = float(f.readline())
循环:f
将是一个封闭的文件句柄,你不能从读
其他提示
以及那里有一对夫妇的事情...
您open(money.txt)
while循环之外,但你第一次迭代后关闭它...
(技术上你关闭,重新打开和再次关闭)
把当环路前来所述第二时间,f
将被关闭,f.readLine()将最有可能失败
仅当满足 IF 条件时才关闭文件,否则您将尝试在 IF 块之后重新打开它。根据您想要实现的结果,您需要删除 f.close 调用,或者添加 ELSE 分支并删除第二个 f.open 调用。无论如何,让我警告您,IF 块中的 str(now) 已被弃用,因为您没有在任何地方保存该调用的结果。
您会得到您的第一行的IO错误,如果money.txt不存在。
我可以捎带一个问题吗?下面已经困扰了我一段时间。我总是从这些“开放()”语句得到一个IO错误,所以我停止检查错误。 (不喜欢这样做!)这有什么错我的代码?的“如果IO错误:”在注释中示出测试是最初与该语句后右“打开()”
。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)
不隶属于 StackOverflow