[Tutor] adding more text to a file

Magnus Kriel magnus.kriel at gmail.com
Sun Jan 17 19:01:03 CET 2010


Hi,

It is the way you open the text file in the beginning.

This is from the python manual:

open() returns a file object, and is most commonly used with two arguments:
"open(filename, mode)".

>>> f=open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>

The first argument is a string containing the filename. The second argument
is another string containing a few characters describing the way in which
the file will be used. mode can be 'r' when the file will only be
read, 'w'for only writing (an existing file with the same name will be
erased), and
'a' opens the file for appending; any data written to the file is
automatically added to the end. 'r+' opens the file for both reading and
writing. The mode argument is optional; 'r' will be assumed if it's omitted.

You should use 'a' and not 'w'.

It might be that when you create a file for the first time with 'a', that it
will through an exception. So you will have to try with 'w', and if there is
an exception, you know the file does not exist and you will have to create
the file for the first time with 'w'.

Hope it helps.

Buy the way, why don't you try sqlite for your database structure? sqlite is
still a single file, not like MySQL. You get a pysqilte at :
http://pypi.python.org/pypi/pysqlite/

Magnus Kriel



The 'W' means write. An 'A' means append

On Sun, Jan 17, 2010 at 9:40 AM, Shizuha Aki <shizuhaaki1 at yahoo.com> wrote:

> Hi,
>
> I am new to python, and i am trying to make a program that makes like a txt
> file database. so i have my whole program in a while True loop, it asks for
> information about the person and then writes the information about the
> person to a txt file, but 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")
>        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
>
> now i want to add like say 5 persons to the txt file, but whenever i enter
> a new person it just overwrites the previous, im sure its because of the "w"
> but how exactly do i need to change my code to add more text instead of
> overwriting?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100117/4153efbb/attachment-0001.htm>


More information about the Tutor mailing list