1

So, I have this is in my CSV file:

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

This is the code:

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

How do I write this piece of information into the CSV file without removing anything? Every time I run the program, the file just contains this piece of info. The rest of it disappears. I want to change to something like:

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
OldWizard007
  • 370
  • 1
  • 8
  • 1
    Have a look at the different [`open` modes](https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function). – ForceBru Feb 08 '21 at 05:57

1 Answers1

0

you should use append mode('a') instead of write mode('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()
Dharman
  • 30,962
  • 25
  • 85
  • 135
RandomGuy
  • 96
  • 3
  • "*else it appends directly to last line*" -- yes, assuming the file doesn't already end in a newline. If it does, then this introduces a blank line into the CSV file. Robust code would check & insert a newline only if needed. – costaparas Feb 08 '21 at 06:25
  • yeah ig that would be better – RandomGuy Feb 08 '21 at 06:30