如何通过命令行填充csv文件中的新列

时间:2015-06-07 20:31:57

标签: python csv

我有这个文本文件: -

User_ID,Date,Num_1,Num_2,Com_ID
101,2015-04-13,12,21,1011
102,2014-04-03,1,7,1002

我正在输入文件中进行一些基本操作并将其写回sample_output.txt文件。

#!/bin/usr/python
import datetime
import csv
import sys
file_name='sample.txt'
with open(file_name,'rb') as f:               
    reader = csv.reader(f)  
    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])
with open('sample_out.txt', 'wb') as ofile:     
        header = ['User_ID','Date','Num_1','Num_2','Com_ID','Dept','Location']
        writer = csv.DictWriter(ofile, fieldnames=header)
        writer.writeheader()
        col_fill = ''
        writer.writerows({col:row_item for row_item,col in zip(row+[col_fill]*n,header)} for row in p)

我需要在输出文件(sample_out.txt)中添加两个新列,并通过命令行传递这两列的值,以便在运行脚本时: - python script.py BUS SAF输出应为: -

User_ID,Date,Num_1,Num_2,Com_ID,Dept,Location
000101,04-13-2015,000012,000021,001011,BUS,SAF
000102,04-03-2014,000001,000007,001002,BUS,SAF

我可以创建新列。如何通过命令行传递值来填充新列。

1 个答案:

答案 0 :(得分:1)

这与我的other post非常相似,我也回答了......在这里,我使用argparse库为您提供输入选项,如:

$ python pyscript.py -cl Dept Location -vl BUS SAF

您也可以使用:

$ python pyscript.py --column_names Dept Location --fill_values BUS SAF

这是代码:

import argparse

# parse arguments from commandline if available
parser = argparse.ArgumentParser()
parser.add_argument('-cl', '--column_names', default=None, nargs='+', type=str)
parser.add_argument('-vl', '--fill_values', default=None,  nargs='+', type=str)

extra_headers = parser.parse_args().column_names
col_fill = parser.parse_args().fill_values

# make sure col_fill is the same length as extra_headers    
if len(col_fill) == len(extra_headers):
    raise ValueError('Wrong number of column fills for number of headers!')
header.extend(extra_headers)

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

# extend p with two columns of blank data
writer.writerows({col: row_item for row_item,col in zip(row+col_fill,header)} for row in p)