I have less than a year of programming experience. While learning about reading and writing files I came across this tutorial: http://www.penzilla.net/tutorials/python/fileio/
The tutorial offers the following example as a simple script to create and write to a file:
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
done = 0
namelist = []
while not done:
name = raw_input("Enter a name:")
if type(name) == type(""):
namelist.append(name)
else:
break
# Create a file object:
# in "write" mode
FILE = open(filename,"w")
# Write all the lines at once:
FILE.writelines(namelist)
# Alternatively write them one by one:
for name in namelist:
FILE.write(name)
FILE.close()
I copied this code and ran it through a Python 2.7.3 Shell. I am prompted repeatedly to enter strings which are appended to a list that will be written to a file (this makes sense to me). What I don't understand is the condition for exiting the While loop ("While not done:"). I thought this meant that I type done at the prompt to exit the loop and subsequently write the file, but done has no effect. Then I thought that any non-string entered at the prompt should break the loop and write the file. I couldn't get the loop to break at all; for anything I entered at the prompt, I was just prompted again with "Enter a name:".
By removing the While loop and retaining the if/else statement, I got the code to work for a single prompt. Can someone tell me what I am not understanding here? I am guessing it is a fairly simple concept that wasn't explained in the tutorial because it was assumed to be obvious. Since "done" is such a common word, I wasn't able to find any Python specific meanings for it.
I would stop following that tutorial right now. The code isn't Pythonic, it's way too complicated, and it seems to be pretty outdated.
That being said, here's how I'd write that tutorial's code (yes, it does the same thing, but only the right way):
with open('test.dat', 'w') as handle:
while True:
name = raw_input('Enter a name: ')
if not name:
break
handle.write(name + '\n')
done
is assigned once on line 3:
done = 0
Therefore, this the while loop will continue to loop as long as done is still "not 0":
while not done:
I.e. it will continue to loop forever, unless it hits a break
statement (line 11). Unfortunately, the code is flawed and that will never happen.
If you want to stop when you type 'done', then change the if statement to:
if name == "done":
But, be aware that the literal string done
above has nothing to do with the variable done
assigned earlier.
It's not your fault. That code provides no way to break out of the loop.
if name == 'end':
break
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With