Skip to content Skip to sidebar Skip to footer

How To Add New Column(header) To A Csv File From Command Line Arguments

The output of the following code:- import datetime import csv file_name='sample.txt' with open(file_name,'rb') as f: reader = csv.reader(f,delimiter=',')

Solution 1:

see this post which suggests something like the following:

header = ['User_ID','--Date','0Num_1','0Num_2','Com_ID']
writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()
writer.writerows({col: row} for row, col in zip(header, p))

to parse the extra columns from the system arguments use sys.argv

import sys

extra_headers = sys.argv
header.extend(sys.argv)
n = len(sys.argv)

writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()

col_fill = ''
# extend p with two columns of blank datawriter.writerows({col: row_item} for row in p for row_item,col in zip(row+[col_fill]*n,header))

here I iterate through each row, I then crate a dictionary to allocate data to each column in order. Notice [col_fill]*n this creates a list of identical items equal to col_fill that will be used to fill the additional columns parsed in via command line arguments.

In this example the command line arguments would be parsed as:

$ python script_name.py Dept_ID Location

and would create:

User_ID,--Date,0Num_1,0Num_2,Com_ID,Dept_ID,Location
000101,04-13-2015,000012,000021,001011,,
000102,04-03-2014,000001,000007,001002,,
000103,06-05-2013,000003,000004,000034,,
000104,12-31-2012,000004,000009,001023,,
000105,09-09-2011,000009,000005,000104,,

Solution 2:

you can use sys.argv to get arguments from command line.

import sys

print'Number of arguments:', len(sys.argv), 'arguments.'print'Argument List:', str(sys.argv)

$ python script_name.py Dept_ID Location

Number of arguments: 4 arguments.
Argument List: ['script_name.pyy', 'Dept_ID Locatio']

after you get the argument from command line, you could add it into your file

Post a Comment for "How To Add New Column(header) To A Csv File From Command Line Arguments"