如何从命令行参数向csv文件添加新列(标题) [英] How to add new column(header) to a csv file from command line arguments
问题描述
以下代码的输出:
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)
如下: -
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
我要为csv添加一个新列文件从命令行。
例如 python script_name.py Dept_ID位置会为Comp_ID旁边的Dept_ID和位置创建列。
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!
推荐答案
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))
从系统参数解析额外的列use sys.argv
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 data
writer.writerows({col: row_item} for row in p for row_item,col in zip(row+[col_fill]*n,header))
这里我遍历每一行,然后创建一个字典,按顺序将数据分配给每一列。注意 [col_fill] * n
这会创建一个等于 col_fill
的相同项目的列表,
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
/ p>
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,,
这篇关于如何从命令行参数向csv文件添加新列(标题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!