Raghavendra Bhargava Raghavendra Bhargava - 2 months ago 14
Python Question

Rename CSV File Headers using Dynamic String in Python

Below is the CSV file structure that I have,

ITEM | ID | SET | COUNT |
------ | ------ |------ | ------ |
Value | 44000001005 | 0 | 24 |
Value | 10000000019659 | 0 | 29 |
Value | 10000000019659 | 1 | 5 |


I want to Dynamically take an input from the user to edit the header, So if I assume that I have taken "Edit_" as input from the user, my resultant CSV file would look like below,

EDIT_ITEM | EDIT_ID | EDIT_SET | EDIT_COUNT |
------------| ---------------|----------- | ------------|
Value | 44000001005 | 0 | 24 |
Value | 10000000019659 | 0 | 29 |
Value | 10000000019659 | 1 | 5 |


So each header value is to be appended by the user input "Edit_". I could manually do this using "w.writerow", but not sure how to dynamically append the user input.

I am relatively new to Python, tried to go through a lot of answers here on Stack Overflow but couldn't get anything that could work for me. I would appreciate any guidance for this issue.

Thank you!

Answer

Use the csv module to read and edit the header then write all the rows back to the new file

import csv
with open("input.csv") as f, open("output.csv", "wb") as o:
    ui = raw_input("Enter  user input: ")
    reader = csv.reader(f)    
    header = reader.next()
    writer = csv.writer(o)
    new_header = map(lambda x:"{}{}".format(ui,x) ,header)
    writer.writerow(new_header)
    writer.writerows(reader)