Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python - 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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...