user2934349
user2934349

Reputation: 21

IOError: File not open for reading python

This is what I have so far, everything I try keep stating that the file isn't open? Is there any basic way to fix this?

liNames = []
while 1 == 1:
    liNames += [raw_input("Tell me a name. Type DONE(all caps) if done entering:")]
    if "DONE" in liNames:
        break

del liNames[-1]

print liNames

name_file = open("names.txt","w")
line = name_file.writelines(liNames)
for line in name_file:
    print line
name_file.close()

Upvotes: 1

Views: 6986

Answers (3)

aIKid
aIKid

Reputation: 28312

Solving your error:

You're only opening it in writing mode, to read it, open it in read mode:

name_file = open("names.txt", "r")

Or just:

name_file = open("names.txt")

Since python opens file in reading mode by default.

So the steps are:

  1. open the file in write mode.
  2. write to it.
  3. close it.

After that, to read the file:

  1. re-open it in read mode.
  2. read it.
  3. close it.

In short, like this:

name_file = open("names.txt","w")
line = name_file.writelines(liNames)
name_file.close()
name_file = open("names.txt")

for line in name_file:
    print line
name_file.close()

To make thing look neater, use the with statement (It will automatically close the file)

Like this:

with open('names.txt', 'w') as file_name:
    line = name_file.writelines(liNames)

with open('names.txt', 'r') as file_name:
    for line in name_file:
        print line    

Upvotes: 0

heltonbiker
heltonbiker

Reputation: 27615

As Tim Peters said, when you open the file in your code, you open it for writing. When you finish writing, the file remains open in this mode until you call "close()" in the last line.

As pointed, you should do this (one possible way):

name_file = open("names.txt","w")
line = name_file.writelines(liNames)
name_file.close()

name_file = open("names.txt")
for line in name_file:
    print line
name_file.close()

Another way is using with statement:

with open("nmes.txt", "w") as name_file:
    name_file.writelines(liNames)

This closes the file automatically when the with block finishes.

Upvotes: 0

Tim Peters
Tim Peters

Reputation: 70735

To be concrete about what the comments have suggested, after this line:

line = name_file.writelines(liNames)

insert these new lines:

name_file.close()
name_file = open("names.txt", "r") # or plain open("names.txt")

With more experience, you'll write this as:

with open("names.txt","w") as name_file:
    name_file.writelines(liNames)
with open("names.txt") as name_file:
    for line in name_file:
        print line

With even more experience ;-), you'll learn how to open a file for both reading and writing. But that's trickier, and especially tricky for text files on Windows.

Upvotes: 1

Related Questions