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?

3
  • 7
    txt.close();txt_again.close(). Btw you're not closing variables. You're closing the file objects. Commented Jul 31, 2014 at 20:05
  • Note that with can be used to alleviate manually management. e.g see docs.python.org/3/reference/… , stackoverflow.com/questions/4042995/… Commented Jul 31, 2014 at 20:09
  • even better, use with, which will handle the closing for you even in case of exception. Commented Jul 31, 2014 at 20:09

4 Answers 4

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.

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

Comments

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.

Comments

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.

Comments

1

Use txt.close().

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.