[Tutor] adding more text to a file

Alan Gauld alan.gauld at btinternet.com
Mon Jan 18 02:24:21 CET 2010


"Shizuha Aki" <shizuhaaki1 at yahoo.com> wrote

> i need it to be able to add more entries instead of just one.
> 
> my code is like this:
> 
> while True:
>       name = raw_input("what is the name ")
>       age = raw_input("what is the age ")
> 
>       out_file = open("persons.txt", "w")

It would work if you moved the open() call outside the loop 
so the file is only opened once. Every time you open the file 
you create a new file on top of the old one. You need to 
move the close outside the loop too of course. That way 
you don't need append mode unless you want to run the 
program multiple times to keep adding data.

>       out_file.write("name: ")
>       out_file.write(name)
>       out_file.write("\n")

You should join the strings together and write a full line out at once. 
It will be more efficient and possibly more resilient too.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list