Reputation: 21
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
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:
After that, to read the file:
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
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
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