pythoncsvdictionaryopencsv

CSV file save fieldnames each time I run the code while converting dictionary to CSV


so i am attempting to convert dictionary to csv. i want it to append to the same csv file each time for that i used "a" mode. but the issue is each time i run the code it is also writing the keys of dictionary as row. following code and screenshot attached explains the situation

def is_known():
    with open("data/data_known.csv", "a",newline="") as f:
            writer = csv.DictWriter(f, fieldnames=current_card.keys())
            writer.writeheader()
            writer.writerow(current_card)

here current_card is a dictonary generated each time from another csv using the following code

global data
data = pandas.read_csv("data/data_unknown.csv")
to_learn = data.to_dict(orient="records")
global current_card
current_card = random.choice(to_learn)
print(current_card)

screenshot for reference

any help is appreciated!


Solution

  • Only add header if file doesn't exist - one way to check is with os.path.isfile

    # import os
    
    def is_known():
        input_fp = "data/data_known.csv"
        is_new_file = not os.path.isfile(input_fp)
        with open(input_fp, "a", newline="") as f:
                writer = csv.DictWriter(f, fieldnames=current_card.keys())
                if is_new_file: 
                    writer.writeheader()
                    is_new_file = False ## update flag in case this is in a loop
                writer.writerow(current_card)