Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - reading text from a file

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?

like image 919
JohnSmith Avatar asked Oct 18 '12 22:10

JohnSmith


People also ask

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do I read a text file?

To read from a text fileUse the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.


1 Answers

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() which was changed in Python 3:

    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 and have it handled when the block ends:

with open(filename) as txt:
    # do stuff needing txt
# txt is closed here
like image 145
Brendan Long Avatar answered Nov 03 '22 01:11

Brendan Long