aSea
aSea

Reputation: 91

python not writing to file for initial run

I have a super simple code and when run the first time it does not write to the file. But when run a second/multiple times later it writes to the file. The same thing happens when using "w" instead of "a" as well.

It also seems that the file is not closed after fh.close is run because I am unable to delete it - and a message appears saying that python is using the file. Any suggestions? Thanks!

fh = open("hello.txt","a")
fh.write("hello world again")
fh.close

Upvotes: 0

Views: 276

Answers (3)

Christer Nissen
Christer Nissen

Reputation: 485

The other posters are correct.

Also, I would suggest using the "with" statement when working with files, because then they will be automatically closed when your code goes out of scope.

with open("hello.txt","a") as fh:
    fh.write("hello world again")

# Code that doesnt use the file continues here

If you use this, you never have to worry about closing your file. Even if runtime errors occur, the file will still always be closed.

Upvotes: 1

James Kent
James Kent

Reputation: 5933

you need to put the brackets after fh.close else you aren't actually calling the function, and if you are running interactively (i.e. with IDLE) then the interpreter keeps the file open.

so change your last line to:

fh.close()

James

Upvotes: 2

Douglas Leeder
Douglas Leeder

Reputation: 53310

fh.close doesn't call close, it just refers to the function. You need to do fh.close() to call the function.

Upvotes: 2

Related Questions