0

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 

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Duplicate answer as Douglas, please consider deleting. @JamesKent
did not see his answer when i posted, however my answer explains why he is unable to delete the file, so will be leaving it.
1

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.

1 Comment

+1 for mentioning predefined clean-up actions. "After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines" (docs.python.org/2/tutorial/errors.html).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.