【发布时间】:2017-01-25 16:33:44
【问题描述】:
我有一个 CSV,其信息和格式类似于我在下面提供的信息作为示例:
FileType clientid cust_name cust_num cust_email
SL 137856 Jim Smith A756 jim@aol.com
SL 137856 Paul Yung H568 yungster@yahoo.com
SL 137856 Tim Jeffries T478 timbo@gmail.com
SL 137856 Tom Reedy N290 reddy76@gmail.com
我想在第一列之后插入一列并用这样的字符串填充它:
FileType dealerid clientid cust_name cust_num cust_email
SL RB6745 137856 Jim Smith A756 jim@aol.com
SL RB6745 137856 Paul Yung H568 yungster@yahoo.com
SL RB6745 137856 Tim Jeffries T478 timbo@gmail.com
SL RB6745 137856 Tom Reedy N290 reddy76@gmail.com
我目前卡在这段代码上,我过去曾用它在 csv 文件的开头附加一列,我稍微修改了它以使其适合我的目的:
with open(id_append_file_path, 'rb') as inf, open(append_file_path + 'new' + append_file_name, 'wb') as outf:
reader = csv.DictReader(inf)
fields = reader.fieldnames
fields.insert(1, 'dealerid')
writer = csv.DictWriter(outf, fields)
writer.writeheader()
for node, row in enumerate(reader, 1):
row['dealerid'] = dealer_id
writer.writerow(row)
但这些是我打开新 CSV 时看到的结果:
FileType dealerid clientid cust_name cust_num cust_email
SL RB6745 Jim Smith A756 jim@aol.com
SL RB6745 Paul Yung H568 yungster@yahoo.com
SL RB6745 Tim Jeffries T478 timbo@gmail.com
SL RB6745 Tom Reedy N290 reddy76@gmail.com
我对 Python 还是很陌生,所以也许我遗漏了一些东西。我正在使用 Python 2.7.11。
【问题讨论】:
-
旁白:如果您是 Python 新手,最好从现代 Python 入手——Python 2 距离报废仅几年时间。
-
@DSM 我所说的新的意思是我已经断断续续地用 Python 编程了几年,但主要是编写脚本。感谢您的提醒。我的大部分脚本都是用 2.7 编写的。看来是时候更新它们了。
标签: python-2.7 csv