gpt4 book ai didi

python - 替换csv文件python的第一行

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:39 26 4
gpt4 key购买 nike

我需要替换 CSV 文件中的列标题,我不知道列的顺序或数量。例如,该文件可能如下所示:

DN  cn  sn  Name    mail    depart  mobile
data1 data2 data3 data4 data5 data6 data7

或者这个

DN  cn  depart  mobile  sn
data1 data2 data3 data4 data5

我需要复制一列并创建一个新标题,所以最终输出看起来像这样(注意 data1 重复):

user    email   phone   depar   mobile  sn
data1 data1 data2 data3 data4 data5

我正在绕着这个圈子转。使用

import csv

with open('test.csv', 'rb') as csvfile:
r = csv.reader(csvfile, delimiter=',', quotechar='"')
headers=r.next()
for index, heading in enumerate(headers):
if heading == 'mail':
headers[index] = "Username"

我可以很好地更改列标题,并将其写入新文件或现有文件,但是我该如何添加额外的列?


解决方案

感谢 abarnert 在下面的回答,我现在正在使用这段代码,它就像一个魅力:

import csv

with open('test.csv', 'rb') as infile, open('out.csv', 'wb') as outfile:
r = csv.reader(infile, delimiter=',', quotechar='"')
headers=r.next()
for index, heading in enumerate(headers):
if heading == 'mail':
headers[index] = "WorkEmail"
username_index = index

headers.insert(username_index, 'Username')

w = csv.writer(outfile, delimiter=',', quotechar='"')
w.writerow(headers)
for row in r:
if len(row) >= username_index:
row.insert(username_index, row[username_index])
w.writerow(row)

最佳答案

您需要做的就是跟踪找到要复制的列的位置,然后添加它。例如:

# ...
# for ...

if heading == 'mail':
headers[index] = "Username"
elif heading == 'data1':
data_1_index = index

headers.insert(data_1_index, 'data1')

而且我假设您也想复制每一行中的值。但这同样简单。

for row in r:
row.insert(data_1_index, row[data_1_index])
w.writerow(row)

将所有内容放在一起,这是一个完整的程序,可以执行(我认为)您想要的操作:

import csv

with open('test.csv', 'rb') as infile, open('out.csv', 'wb') as outfile:
r = csv.reader(infile, delimiter=',', quotechar='"')
headers=r.next()
for index, heading in enumerate(headers):
if heading == 'mail':
headers[index] = "Username"
elif heading == 'data1':
data_1_index = index
headers.insert(data_1_index, 'data1')

w = csv.writer(outfile, delimiter=',', quotechar='"')
w.writerow(headers)
for row in r:
row.insert(data_1_index, row[data_1_index])
w.writerow(row)

关于python - 替换csv文件python的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com