Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python not creating new file headers when it does not exist

I want to write a new CSV file with headers if it does not exist, and append row data to it. Not sure why the following code doesn’t add the file headers? (Append works fine)

import os
import csv

path = "test.csv"


with open(path, mode="a") as f:    
    writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)

    if not os.path.exists(path):
        writer.writerow(["col1", "col2", "col3", "col4", "col5", "col6", "col7"])

    row = [1,2,3,4,5,6,7]
    writer.writerow(row)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Need to move if exists test before opening the file. Opening the file in "a" mode will create the file if it does not already exist.

import os
import csv

path = "test.csv"

exists = os.path.exists(path)
with open(path, mode="a") as f:    
    writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)

    if not exists:
        writer.writerow(["col1", "col2", "col3", "col4", "col5", "col6", "col7"])

    row = [1,2,3,4,5,6,7]
    writer.writerow(row)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading