如何写入CSV文件而不删除Python中的任何内容?



我的CSV文件中有如下内容:

app,ceo,date,type
Youtube,Susan Wojcicki,2005,video sharing
Facebook,Mark Zuckerburg,2004,social networking
Google,Sundar Pichai,1998,search engine
Amazon,Jeff Bezos,1994,e-commerce
Apple,Tim Cook,1976,tech

这是代码:

data = open('companies.csv', 'w')
data.write(",".join(["Tesla", "Elon Musk", "2003", "automative"]))
data.close()

我如何将这段信息写入CSV文件而不删除任何内容?每次我运行程序时,文件只包含这条信息。剩下的就消失了。我想改成这样:

app,ceo,date,type
Youtube,Susan Wojcicki,2005,video sharing
Facebook,Mark Zuckerburg,2004,social networking
Google,Sundar Pichai,1998,search engine
Amazon,Jeff Bezos,1994,e-commerce
Apple,Tim Cook,1976,tech
Tesal,Elon Musk,2003,automotive

你应该使用追加模式('a')而不是写入模式('w')

data = open('companies.csv', 'a')
data.write("n") #else it appends directly to last line
data.write(",".join(["Tesla", "Elon Musk", "2003", "automative"]))
data.close()

相关内容

  • 没有找到相关文章

最新更新