How to add new column(header) to a csv file from command line arguments

2024/9/20 13:26:18

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=",")                                              #headers = reader.next()p=[]for row in reader:row[0] = row[0].zfill(6) row[2] = row[2].zfill(6)row[3] = row[3].zfill(6)row[4] = row[4].zfill(6)row[1] = row[1][5:7] + "-" + row[1][8:10] + "-" + row[1][:4]p.append(row[:5])print p
with open('names.txt', 'wb') as ofile:writer = csv.writer(ofile)for row in p:writer.writerow(row)

is following:-

User_ID,--Date,0Num_1,0Num_2,Com_ID
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

I want to add a new column to the csv file from command line. e.g. python script_name.py Dept_ID Location will create columns for Dept_ID and Location next to Comp_ID.

Can any one guide me here please!

Answer

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 sysextra_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 data
writer.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,,
https://en.xdnf.cn/q/119325.html

Related Q&A

Pattern matching and replacing in Python

Im trying to take a string that can be anything like "Hello here is a [URL]www.url.com[/URL] and its great." and be able to extract whatever is between [URL] and [/URL] and then modify the st…

In Python word search, searching diagonally, printing result of where word starts and ends

I have a friend of mine tutoring me in learning Python and he gave me this project where a user will read a word search into the program and the file includes a list of words that will be in the word s…

Selenium python : element not interactable

I am trying to scrape information from this website example website I need to get the version 2021 and search by code. Here is my code: from selenium import webdriver from selenium.webdriver.chrome.opt…

Date into matplotlib graph

How can I use a date from a Sqlite database on the x-axis to make a bar graph with matplotlib?If I convert the date to unix timestamp the graph works, but I would like to get something like this: http…

Non blocking IO - Programming model

In non blocking IO programming model, a thread blocked on data available channels, as shown below, in python,while True:readers, _, _ = select.select([sys.stdin, sock], [], []) # blocked select()for re…

How to globally change xticks label relplot in Seaborn

I am facing an issue to globally changed the x-tick label for plot render using the relplot The idea was to change the int to string x-tick label for both plot. The desired label is [a,b,c,d] However, …

How to solve MatplotlibDeprecationWarning: scipy.stats.norm.pdf warning?

I am using matplotlib in my Python code. I got following warning: xxx.py:88: MatplotlibDeprecationWarning: scipy.stats.norm.pdfy = 100 * mlab.normpdf(bin_middles, mu, sigma)*bin_width I was wondering…

time data 42:53.700 does not match format %H:%M:%S.%f (match)

I am trying to convert a column in string format to DateTime format, However, I am getting the following error, could somebody please help? The error:time data 42:53.700 does not match format %H:%M:%S…

How can I import .py file? [duplicate]

This question already has answers here:Adding a directory to sys.path with pathlib(4 answers)Closed last year.Below is my code: from pathlib import Path import os import sys sys.path.insert(0, os.path.…

python: convenient way to create list of strings of repeated elements

How can I create a list like this:["a","a","a",... (repeating "a" a hundred times") "b","b","b",(repeating "b" a hun…