Reputation: 66
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()
Upvotes: 0
Views: 72
Reputation: 48077
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:
with
, Python will take care of closing the file.close()
. Refer: PEP 343 -- The "with" Statement. Also check Trying to understand python with statement and context managers to know more about them.
Upvotes: 4