I have less than a year of programming experience. Studying reading and writing files, I came across this lesson: 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 create a file and write it to disk. filename = "test.dat" # Let 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 the Python 2.7.3 shell. I am repeatedly asked to enter lines that are added to the list that will be written to the file (this makes sense to me). What I do not understand is the condition for exiting the While loop ("Not yet done:"). I thought this meant that I was typing in the prompt to exit the loop and subsequently write the file, but this has no effect. Then I thought that any line entered at the prompt should break the loop and write the file. I could not make the loop break at all; for anything that I entered in the prompt, I was again offered to "Enter a name:".
By removing the While loop and saving the if / else statement, I got the code to work in a single prompt. Can someone tell me what i don't understand here? I suppose this is a fairly simple concept that was not explained in the textbook because it was supposed to be obvious. Since "done" is such a common word, I could not find any Python-specific meanings for it.
source share