pythonpython-3.xpython-2.7csvcsv-write-stream

how to add header to existing csv files using python without rewrite all the existing content


I am trying to add a header to my existing csv file and there are already content in it. I am just wondering if there is any piece of code that could insert a header row at the top (such as ['name','age','salary','country'] without affecting the contents.

Also this code is connected to API so I will run it multiple times. So just wondering if it is possible to detect whether a header exists to avoid multiple header lines.

THank you and hope you all a good day!


Solution

  • Your question has 2 parts:

    1) To add a header to your csv (when it does not exists) In order to insert the header row, you can read the csv with below command:

    df=pd.read_csv(filename, header=None, names=['name','age','salary','country'])
    

    To get create the csv with header row without affecting the contents you can use below command

    df.to_csv(new_file_with_header.csv, header=True)
    

    2) The second parti is little tricky. To infer whether your file is having header or not you will have to write a little code. I can provide you the algorithm.

    read csv explicitly with header

    df=pd.read_csv(filename.csv, header=None, names=['name','age','salary','country'])
    

    Check for 1st row 1st column in your csv, if it contains value as 'name' then write the csv from 2nd row till end else write as is

    temp_var=df['name'].iloc[0]
    
    if (temp_var=='name'):
      df.iloc[1:].to_csv(new_file.csv)
    else:
      df.to_csv(new_file.csv)
    

    Hope this helps!!

    Thanks, Rohan Hodarkar