Newbie Python Script - read()
Question: I am trying to learn more about python and wrote a simple script but I can't
get the read() function to work. What am I missing? The error message I am
getting is:

Traceback (most recent call last): File "ex16demo.py", line 28, in print
glist.read() IOError: File not open for reading

I file should be open and assigned to the glist variable.

    
    
    from sys import argv
    
    script, filename = argv
    
    print "We are creating a new grocery list!"
    
    print "Opening %r..." % filename
    glist = open(filename, 'w')
    
    print "Deleting previous content from %r......" % filename
    glist.truncate()
    
    print "Add your items now:"
    item1 = raw_input("item 1:")
    item2 = raw_input("item 2:")
    item3 = raw_input("item 3:")
    
    print "Adding your items to the list...."
    glist.write(item1)
    glist.write("\n")
    glist.write(item2)
    glist.write("\n")
    glist.write(item3)
    glist.write("\n")
    
    print "Here are the items in your grocery list:"
    
    print glist.read()
    

Thanks!


Answer: The file was opened for writing (see `open(filename, 'w')`).

Close the file, open it for reading and then call `read()`:

    
    
    glist.close()
    
    glist = open(filename, 'r')
    print glist.read()
    

Or, you can open file in `r+` mode to read and write without reopening (thanks
to @sberry's comment).

Also, consider using `with` context manager instead of manually closing the
opened file:

    
    
    with open(filename, 'r+'):
    
        print "Deleting previous content from %r......" % filename
        glist.truncate()
    
        ...
    
        print glist.read()
    

Also see:

  * [documentation](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) on `open()` modes
  * [python open built-in function: difference between modes a, a+, w, w+, and r+?](http://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r)

