Home > Software design >  saving python variable to csv
saving python variable to csv

Time:06-16

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!

CodePudding user response:

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

CodePudding user response:

Just replace 'w' by 'a' where 'w' writes in file (override) while 'a' appends the file whenever you write in it.

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

For the header "email" just write it before you add the loop of emails to do not duplicate it

CodePudding user response:

Read the file contents first; add the new data; write the data to a file.

def hello(hme):
    try:
        with open('countries.csv', encoding='UTF8', newline='') as f:
            stuff = list(csv.reader(f))
    except FileNotFoundError:
        # this must be the first time the function was called
        stuff = [['email']]
    stuff.append([hme])

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

If your file really only has one column you don't really need to use the csv module. Just append the new line to the file.

# assumes header is present
def hello(hme):
    with open('countries.csv', 'a', encoding='UTF8') as f:
        f.write(hme   '\n')
  • Related