Python generates I / O error when interleaving open / close / readline / write on the same file

I am learning Python - this is giving me an I / O error -

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()

      

Thanks!

+1


a source to share


5 answers


while True

will loop forever unless you split it by break

.



The I / O error is probably due to the fact that when you skip the loop, once the last thing you do is f.close()

which closes the file. When execution continues with a loop on line currentmoney = float(f.readline())

: f

will be a closed file descriptor from which you cannot read.

+3


a source


well, here are a couple of things ...

you are open(money.txt)

outside of the while loop, but you close it after the first iteration ... (technically you close, reopen and close)



Put when the loop appears a second time f

will be closed and f.readLine () will most likely fail

+2


a source


You only close the file if the IF condition is satisfied, otherwise you try to reopen it after the IF block. Depending on the result you want to achieve, you need to either remove the f.close call, or add an ELSE branch and remove the second f.open call. Anyway, let me warn you that the str (now) in your IF block is simply deprecated, since you don't store the result of that call anywhere.

0


a source


You will get an IO Error on your first line if money.txt doesn't exist.

0


a source


May I ask a question? The following has puzzled me for some time now. I always get IOError from these open () statements, so I stopped checking for an error. (Don't like doing this!) What's wrong with my code? The "if IOError:" test shown in the comments was originally after being asserted with "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)

      

0


a source







All Articles