2

I am trying to make a program that will take the answers of what the user inputted and put it in a text document in Python 2.7. I have the problem of when running the program again, the text document is overwritten and the previous data was deleted. So I was wondering how to avoid this problem. If this was already answered, please link the article. Thanks a bunch in advance!

import time
import sys as LOL
print 'Welcome to the database, enter -1 to exit.'
time.sleep(1)
files = open('c:/writing.txt','w')
name = raw_input('Enter in your name... ')
if name == '-1':
    LOL.exit()
time.sleep(1)
if len(name)> 64 or len(name)< 1:
    print 'Please enter a name that is between 1 and 64 characters!!'
while len(name)>64 or len(name)<1:
    name = raw_input('Enter in your name... ')
    if name == '-1':
        LOL.exit()
    if len(name)> 64 or len(name)<1:
        print 'Please enter a name that is between 1 and 64 characters!!'
        time.sleep(1)
time.sleep(1)
age = int(raw_input('Enter in your age... '))
if age == -1:
    LOL.exit()
while age > 125 or age < 1:
    age = int(raw_input('Enter in your age... '))
    if name == '-1':
        LOL.exit()
    time.sleep(1)
    if age > 125 or age < 1:
        print 'Enter in a vaild age!'
newedit = name + ' is %s years old.' %age
files.write(newedit)
files.close()
user3709398
  • 85
  • 1
  • 5

2 Answers2

6

That is because you opened the file in w mode (write mode). As you can read in the docs, doing so automatically truncates it:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position).

As the excerpt above says, you should use a mode to append text to a file without truncation:

files = open('c:/writing.txt','a')
4

An append 'a' rather that write 'w' mode should probably do it so you use the line f = open("text.txt", 'a').

Nobi
  • 1,113
  • 4
  • 23
  • 41