Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to CSV and not overwrite past text

The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)

def main(src):
    try:
        input_file = open(src, "r")
    except IOError as error:
        print("Error: Cannot open '" + src + "' for processing.")
    print("Welcome to Learner!")
    print("What is your name? ")
    name = input()
    for line in input_file:
        w = line.split(",")
        for x in w:    
            if x.lower() == name.lower():
                print("I remember you "+ name.upper())
            else:
                print("NO")
                a = open("learner.csv", "w")
                a.write(name)
                a.close()
                break
if __name__ == "__main__":
    main("learner.csv")
like image 684
user1775500 Avatar asked Nov 02 '12 22:11

user1775500


3 Answers

You need to append to file the next time. This can be done by opening the file in append mode.

def addToFile(file, what):
    f = open(file, 'a').write(what) 
like image 70
Kartik Avatar answered Oct 27 '22 09:10

Kartik


change open("learner.csv", "w") to open("learner.csv", "a")

The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.

like image 24
evanmcdonnal Avatar answered Oct 27 '22 08:10

evanmcdonnal


You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.

Also, you might want to consider using the with keyword:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

>>> with open('/tmp/workfile', 'a') as f:
...     f.write(your_input)
like image 21
lfk Avatar answered Oct 27 '22 09:10

lfk