Python Forum

Full Version: Insert header at first row, for existing csv
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,

I have input data in csv file like below.

1,EAST,100
2,WEST,200
3,SOUTH,300
4,NORTH,400


I want to add these headers to above input file at line one.
ID,Region,Salary


Final should look like this.

Add headers to csv
ID,Region,Salary
1,EAST,100
2,WEST,200
3,SOUTH,300
4,NORTH,400

with open("data1.csv","w") as f:
f.write()
psuedo code:
  • Open input file for reading and output file for writing with open('infilename', 'r') as fin, open("data1.csv","w") as fout:
  • Create a list with header
  • Write header
  • Do until finished:
    • read input record
    • write output record
  • Done
Hi Larz60,

Thanks for your help,

Actually I am extracting SQL Table data into CSV. using bulk copy method.
I am getting all data without header.
I am thinking of adding header after download. but it is overwriting existing data.

is there way we can do bulk copy sql data with header.
file size if big 60gb.


source_table = "xxx_xxxx_xxx_POC.dbo.Table1"
destination = str(Path("E:\test\table1.csv"))
subprocess.run(["bcp", source_table, "out", destination,  "-ABCD12345678\\ABCD5678,10010","-c", '-t"|"', "-T" ])




in both the below solution data gets overwritten or it adds records at end of file.


import fileinput

for line in fileinput.input(files=["my-file.csv"], inplace=True):
    if fileinput.isfirstline():
        print('first,second,third,fourth')
    print(line, end="")

from csv import writer
from csv import DictWriter
def append_list_as_row(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)