[Tutor] adding more text to a file

Modulok modulok at gmail.com
Mon Jan 18 16:54:53 CET 2010


If you're using this as an interactive command to help you populate a
database, as you appear to be, don't open the file more than once. As
previously suggested you should also put all your strings together and
then write them to the database in one go.

I don't know if you've thought about this yet, but you'll need a way
to stop when you're done inputing names and ages! Here are two
thoughts you can look into: 1) Check for a special character (or lack
thereof). For example, if the fields are blank you could exit the loop
using the 'break' statement. Or 2) Catching a 'KeyboardInterrupt'
exception using the 'try...except' statements. Without doing it for
you, (I assume this is homework) these are some suggested changes:

out_file = open('persons.txt', 'w')
while True:
    name = raw_input("What is the name: ")
    age = raw_input("What is the age: ")
    out_file.write("name:%s\nage: %s\n\n" (name, age))

# We'll never get this far unless we figure out a way to stop the loop!
out_file.close()


Keep at it and best of luck!
-Modulok-


More information about the Tutor mailing list