Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过命令行在csv文件中填充新列_Python_Csv - Fatal编程技术网

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

Python 如何通过命令行在csv文件中填充新列,python,csv,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 我正在对输入文件进行一些基本操作,并将其写入示例_output.txt文件 #!/bin/usr/python import datetime import csv import sys file_name='sample.txt' with open(file_name,'rb') as f:

我有这个文本文件:-

User_ID,Date,Num_1,Num_2,Com_ID
101,2015-04-13,12,21,1011
102,2014-04-03,1,7,1002
我正在对输入文件进行一些基本操作,并将其写入示例_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

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

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

$ python pyscript.py -cl Dept Location -vl BUS SAF
$ python pyscript.py --column_names Dept Location --fill_values BUS SAF
您还可以使用以下命令:

$ 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)

sed'1!s/$/,总线,SAF/'file@satyaki-我还添加了一些错误处理,您可能需要避免错误创建垃圾文件。如果我的解决方案对你有帮助,你能接受我的答案吗?我得到的输出如下:-
User\u ID,Date,Num\u 1,Num\u 2,Com\u ID,python\u poc1.py,-c,Dept,Location,-v,BUS,SAF 000101,04-13-20150000120000201011,BUS,SAF,,,
添加
print col fill
print extra\u header
?另外,请确保您已将
header
更改为
header=['User\u ID'、'Date'、'Num\u 1'、'Num\u 2'、'Com\u ID']
嘿,修复了它!!谢谢我不明白这一行发生了什么:-
writer.writerows({col:row\u item for row\u item,col in zip(row+col\u fill,header)}for row in p)
。我对它做了一些修改,以适应一些格式问题。请简要解释一下。