Mika H.
Mika H.

Reputation: 4329

Python read/write file without closing

Sometimes when I open a file for reading or writing in Python

f = open('workfile', 'r')

or

f = open('workfile', 'w')

I read/write the file, and then at the end I forget to do f.close(). Is there a way to automatically close after all the reading/writing is done, or after the code finishes processing?

Upvotes: 3

Views: 9770

Answers (3)

Stefan Gruenwald
Stefan Gruenwald

Reputation: 2640

Whatever you do with your file, after you read it in, this is how you should read and write it back:

$ python myscript.py sample.txt sample1.txt

Then the first argument (sample.txt) is our "oldfile" and the second argument (sample1.txt) is our "newfile". You can then do the following code into a file called "myscript.py"

    from sys import argv
    script_name,oldfile,newfile = argv
    content = open(oldfile,"r").read()
    # now, you can rearrange your content here
    t = open(newfile,"w")
    t.write(content)
    t.close()

Upvotes: 0

msegf
msegf

Reputation: 81

You could always use the with...as statement

with open('workfile') as f:
    """Do something with file"""

or you could also use a try...finally block

f = open('workfile', 'r')
try:
    """Do something with file"""
finally:
    f.close()

Although since you say that you forget to add f.close(), I guess the with...as statement will be the best for you and given it's simplicity, it's hard to see the reason for not using it!

Upvotes: 2

HennyH
HennyH

Reputation: 7944

with open('file.txt','r') as f:
    #file is opened and accessible via f 
    pass
#file will be closed before here 

Upvotes: 6

Related Questions