如何写入 CSV 而不是覆盖过去的文本 [英] How to write to CSV and not overwrite past text

查看:52
本文介绍了如何写入 CSV 而不是覆盖过去的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码是我目前所拥有的.当它写入 .csv 时,它会覆盖我之前在文件中写入的内容.如何写入文件以使其不会删除我以前的文本.(我的代码的目标是让一个人输入他们的名字并让程序记住他们)

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

推荐答案

下次需要追加到文件中.这可以通过以追加模式打开文件来完成.

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) 

这篇关于如何写入 CSV 而不是覆盖过去的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆