2

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!

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
user2565554
  • 447
  • 4
  • 13
  • 22

2 Answers2

4

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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

The 'w' in glist = open(filename, 'w') means you're opening the file in 'write' mode. You'll need to close() it and re-open it in 'read' mode (open(filename, 'r')) to print out the contents.

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157