[Tutor] adding more text to a file

wesley chun wescpy at gmail.com
Mon Jan 18 00:17:32 CET 2010


> while True:
>        name = raw_input("what is the name ")
>        age = raw_input("what is the age ")
>
>        out_file = open("persons.txt", "w")
>        out_file.write("name: ")
>        out_file.write(name)
>        out_file.write("\n")
>        out_file.write("age: ")
>        out_file.write(age)
>        out_file.write("\n")
>        out_file.write("\n")
>        out_file.close


while everyone is helping you with your original inquiry, i'm going to
inject some "Pythonic" style guidelines here.

1. i would strongly suggest calling the close() method instead of
merely providing the object. in other words, change your last line to
"out_file.close()" so you execute it. otherwise your file contents are
not guaranteed.

2. try to minimize the total number of calls to write() to make things
run faster. for example, your code only really needs one call:

out_file.write("name: %s\nage: %s\n\n" % (name, age))

the reason why it's faster is because you pay a little bit of overhead
with every function call you make. of course, since your example
requires human input each time, it doesn't make as much of a
difference in this example, but this is mostly a general suggestion.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list