0

I forgot how many times I opened the file but I need to close them I added the txt.close and txt_again.close after I opened it at least 2 times

I'm following Zed A. Shaw Learn Python The Hard Way

#imports argv library from system package
from sys import argv
    #sets Variable name/how you will access it
script, filename = argv
    #opens the given file from the terminal
txt = open(filename)
    #prints out the file name that was given in the terminal
print "Here's your file %r:" % filename
    #prints out the text from the given file
print txt.read()
txt.close()
#prefered method
    #you input which file you want to open and read 
print "Type the filename again:"
    #gets the name of the file from the user
file_again = raw_input("> ")
    #opens the file given by the user
txt_again = open(file_again)
    #prints the file given by the user
print txt_again.read()
txt_again.close()

1 Answer 1

4

In order to prevent such things, it is better to always open the file using Context Manager with like:

with open(my_file) as f:
    # do something on file object `f`

This way you need not to worry about closing it explicitly.

Advantages:

  1. In case of exception raised within with, Python will take care of closing the file.
  2. No need to explicitly mention the close().
  3. Much more readable in knowing the scope/usage of opened file.

Refer: PEP 343 -- The "with" Statement. Also check Trying to understand python with statement and context managers to know more about them.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.