Python Forum
Insert header at first row, for existing csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Insert header at first row, for existing csv
#1
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()
Reply
#2
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
Reply
#3
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)
Larz60+ write Oct-05-2022, 10:10 AM:
Double posting is against forum rules.
Please continue thread rather than adding new ones.
Thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Add\insert header row existing csv files mg24 0 724 Oct-05-2022, 06:11 AM
Last Post: mg24
  Insert a multiple constant value after header in csv file using python shantanu97 1 1,159 Apr-24-2022, 10:04 AM
Last Post: Pedroski55
  Insert using psycopg giving syntax error near "INSERT INTO" olgethorpe 4 15,663 Jul-21-2017, 07:39 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020