How to add a list to the first row of csv files of a particular folder

Viewed 15

There is a folder named data containing multiple csv files but there are no headers to that csv file and hence I have to add headers to the first row of the multiple csv files .

I have the below code which is taking one csv file and adding the list to the last row. I need it to the first row and instead of taking one csv file , it must take all csv files from a folder at once. Can you please help me how to do it?

List = [" ", " "]
with open('.csv', 'a', newline='') as f_object:  
    # Pass the CSV  file object to the writer() function
    writer_object = writer(f_object)
    # Result - a writer object
    # Pass the data in the list as an argument into the writerow() function
    writer_object.writerow(List)  
    # Close the file object
    f_object.close()
1 Answers

No need for the CSV module.

for fn in glob.glob('*.csv'):
    contents = open(fn).read()
    with open(fn,'w') as f:
        print("header1,header2,header3", file=f)
        f.write(contents)
Related