Home > Enterprise >  write on a csv column and change header
write on a csv column and change header

Time:02-18

i'm trying to use python to make a script that change a csv, i have to ask for an input that will be the same for all the lines and also have to change an header name but not all the values listed, here is the script

import csv
location= input("File Path: ")
with open(location) as csv_file:
    csv_reader = csv.DictReader(csv_file)
    with open('fixed.csv', 'w', newline='') as new_file:
        
        fieldnames = "value", "type", "description"
        writer=csv.writer(new_file)

        csv_writer =csv.DictWriter(new_file, fieldnames=fieldnames, delimiter= '|', extrasaction='ignore')
        csv_writer.writeheader()

        for line in csv_reader:
            line = {k: v.replace("sha1", "hash") for k, v in line.items()}
            
   
            if not any("url" in value for value in line.values()):
                csv_writer.writerow(line)

Here is the code, i have to change "value" header to a new word, and list under "description" the same thing that is asked to the user

sample of csv

value|type|description
35|new|
46|new|
54|new|

CodePudding user response:

For the csv writer you need to declare the column names like so.

fieldnames = "new_column_name", "type", "description"

If you are Using python 3.7 replace this line

line = {k: v.replace("sha1", "hash") for k, v in line.items()}

with

line = {"new_column_name" if k == 'value' else k:v.replace("sha1", "hash") for k,v in line.items()}

Otherwise, the following will work for any version. place this code after initializing the line variable

line = {'new_columne_name' : line['value'], 'type': line['type'], 'description' : line['description']}

if you want to change the value of the description at a certain line simply use this

line['description'] = new_value
  • Related