2

I have the following code:

from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()

And in one of the exercises in my book it says "Have your script also do a close() on the txt and txt_again variables. It’s important to close files when you are done with them.

How can I close the variables?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
lay3r
  • 43
  • 1
  • 4
  • 7
    `txt.close();txt_again.close()`. Btw you're not closing *variables*. You're closing the *file objects*. – vaultah Jul 31 '14 at 20:05
  • Note that `with` can be used to alleviate manually management. e.g see https://docs.python.org/3/reference/compound_stmts.html#the-with-statement , http://stackoverflow.com/questions/4042995/python-equivalent-to-cs-using-statement – user2864740 Jul 31 '14 at 20:09
  • even better, use `with`, which will handle the closing for you even in case of exception. – njzk2 Jul 31 '14 at 20:09

4 Answers4

6

txt.close() will close the file parser. However I would suggest the use of with instead:

with open(filename) as txt:
    print "Here's your file %r:" % filename
    print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")
with open(file_again) as txt_again
    print txt_again.read()

This ensures that the file parser is closed correctly and also make for cleaner more pythonic code.

James Mertz
  • 8,459
  • 11
  • 60
  • 87
4

Do txt.close() and txt_again.close() after their respective print statements.

EDIT: As others have already pointed out, using the with statement is a much better option.

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
2

Your book text is being unclear and imprecise. What they want you to do is call the file.close() method on the file objects:

print txt.read()
txt.close()

and

print txt_again.read()
txt_again.close()

A better idea would be to use the with statement to have Python close files for you automatically; file objects are context managers:

with open(filename) as txt:
    print "Here's your file %r:" % filename
    print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

with open(file_again) as txt_again:
    print txt_again.read()

The with statement tells the file object that a block begins (entering the context), and when the indented section ends the statement informs the file object the block has completed (exiting the context). A file object automatically closes itself at that point.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Use txt.close().

It's also worth noting that you are not closing a varibale, but rather a handle on the file.

Philip Massey
  • 1,401
  • 3
  • 14
  • 24