0

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!

4
  • Probably easier to use pandas data frame and then covert to csv through pandas.DataFrame.to_csv Commented Jun 15, 2022 at 13:32
  • if you don't want to overwrite the existing value open the file in append mode Commented Jun 15, 2022 at 13:34
  • 1
    @VRComp Bringing in a pandas dependency seems quite overkill for this simple task… Commented Jun 15, 2022 at 13:35
  • 1
    @NicolasMoreau Good point. I was thinking maybe OP will expand the code to include more rows, which is why I suggested pandas. This could be a simple case and OP wanted to apply it to a larger case later on. Commented Jun 15, 2022 at 15:49

3 Answers 3

1

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]"])
Sign up to request clarification or add additional context in comments.

2 Comments

hi thanks for the response, if i write emails manually and delete writer.writerow(header) and header = ['email'] it outputs like this [email protected] and if i keep the header it outputs email #new row email #new row [email protected]
however if i manually type email #new row it just works fine
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.