【问题标题】:How to write to CSV and not overwrite past text如何写入 CSV 而不会覆盖过去的文本
【发布时间】:2018-04-17 17:17:00
【问题描述】:

下面的代码是我目前所拥有的。当它写入 .csv 时,它会覆盖我之前在文件中写入的内容。我怎样才能以不会擦除我以前的文本的方式写入文件。(我的代码的目标是让一个人输入他们的名字并让程序记住他们)

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

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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

def addToFile(file, what):
    f = open(file, 'a').write(what) 

【讨论】:

    【解决方案2】:

    open("learner.csv", "w") 更改为open("learner.csv", "a")

    open的第二个参数是mode,w是write,a是append。使用 append 它会自动寻找到文件的末尾。

    【讨论】:

      【解决方案3】:

      您需要以附加模式 ('a') 打开文件,而不是写入模式 ('w'); Python documentation 解释了可用的不同模式。

      另外,您可能需要考虑使用 with 关键字:

      在处理文件对象时,最好使用 with 关键字。这样做的好处是文件在其套件完成后会正确关闭,即使在途中引发异常也是如此。

      >>> with open('/tmp/workfile', 'a') as f:
      ...     f.write(your_input)
      

      【讨论】:

        猜你喜欢
        • 2011-05-08
        • 2020-03-28
        • 2012-04-15
        • 1970-01-01
        • 2023-03-28
        • 2014-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多