Python 3 - reading text from a file
Question: This is exercise 15 from Learn Python the Hard Way, but I'm using **Python
3**.

    
    
    from sys import argv
    script, filename = argv
    
    txt = open(filename)
    print ("Here's your file %r:") % filename
    print txt.read()
    
    print ("I'll also ask you to type it again:")
    file_again = input()
    txt_again = open(file_again)
    print txt_again.read()
    

**file is saved as ex15.py, and when I run it from terminal it reads ex15.txt
correctly first time, but when I request it second time, I get an error**

    
    
    user@user:~/Desktop/python$ python ex15.py ex15.txt<br>
    Here's your file 'ex15.txt':<br>
    This is stuff I typed into a file.<br>
    It is really cool stuff.<br>
    Lots and lots of fun to have in here.<br>
    
    I'll also ask you to type it again:<br>
    ex15.txt <b>#now I type this in again, and I get a following error</b><br>
    Traceback (most recent call last):<br>
      File "ex15.py", line 11, in <<module>module><br>
        file_again = input()<br>
      File "<<string\>string>", line 1, in <<module>module><br>
    NameError: name 'ex15' is not defined
    

What's wrong?


Answer: You're definitely not using Python 3. There's a couple things that make this
obvious:

  * These `print` statements don't have parenthesis (which are required in Python 3 but not 2):
    
        print ("Here's your file %r:") % filename
    print txt.read()
    
    print txt_again.read()
    

  * This is calling [`eval` on `input()`](http://docs.python.org/library/functions.html#input) which was [changed in Python 3](http://docs.python.org/release/3.0.1/library/functions.html#input):
    
        file_again = input()
    

Most likely Python 2 is the default on your system, but you can make your
script always use Python 3 by adding this as the first line of your script (if
you're running it directly, like `./myscript.py`):

    
    
    #!/usr/bin/env python3
    

Or running it explicitly with Python 3:

    
    
    python3 myscript.py
    

One more note: You should really close the file when you're done with it. You
can either do this explicitly:

    
    
    txt = open(filename)
    # do stuff needing text
    txt.close()
    

Or use a [`with` statement](http://www.python.org/dev/peps/pep-0343/) and have
it handled when the block ends:

    
    
    with open(filename) as txt:
        # do stuff needing txt
    # txt is closed here
    

