Search code examples
pythoncsvvariables

saving python variable to csv


i am having troubles on this python error. I want to save changing variables to an csv file, however while the code runs again with an different variable it overwrites the previous one. I do not have the variables predetermined, they are generated while the code runs, so every time the loop will loop the program there will a different email passed.

Here is my code:

import csv

def hello(hme):
        header = ['email']
        data = [hme]


        with open('countries.csv', 'w', encoding='UTF8', newline='') as f:
                writer = csv.writer(f)


                writer.writerow(header)
                writer.writerows(data)

hello(["[email protected]"])

Thank you!


Solution

  • you should open the file as append, instead of write: 'a' instead of 'w'

    import csv
    
    def hello(hme):
            header = ['email']
            data = [hme]
    
    
            with open('countries.csv', 'a', encoding='UTF8', newline='') as f:
                    writer = csv.writer(f)
    
    
                    writer.writerow(header)
                    writer.writerows(data)
    
    hello(["[email protected]"])