简体   繁体   中英

How to avoid overwriting a file in python?

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()

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')

附加'a'而不是写'w'模式应该这样做,所以你使用行f = open("text.txt", 'a')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM