[Tutor] adding more text to a file (Vanam)

vanam raghavendra.gv.vanam at gmail.com
Wed Jan 20 19:13:13 CET 2010


Below is the code which can be helpful for better insight:

Sample: 1

For the below code, you can provide initially the number of entries
(say 4) so that for four times name of person and age is prompted to
enter.After writing to file we can read back the contents

#Writing number of times the name of person to a file
#Opening the file
log = open('data.txt','w')
x = int(raw_input('enter the number of entries'))
for y in range(x):
       data = raw_input('enter the name of the person')
       age = int(raw_input('enter age of the person'))
       print  >> log,  '%s %d' % (data,age)
log.close()
#Reading the contents of the file with multiple entries
log = open('hello.txt','r')
for x in log:
       print x,
log.close()

Sample:2
Assuming your query, below is the short piece where name and age is
always entered till there is no data entered for person and the same
content is written back to the file.
log = open('data.txt','w')
while True:
       x = raw_input('enter name')
       if len(x)  == 0:
              break
       y = int(raw_input('enter age'))
       print >> log, '%s %d' % (x,y)
log.close()

>
> 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?
>
>
>
>

-- 
Raghavendra  Vanam


More information about the Tutor mailing list