-1

我是 Python 新手csv.reader,我正在尝试sheet2使用以下标题填充数据sheet1

sheet1.csv包含以下标题

  1         2         3         4         5         6         7  

sheet2.csv包含以下数据

  col_1     col_4     col_5     col_7
 yellow      Blue     Green       Red

所需的输出如下:

      1         2         3         4         5         6         7  
 Yellow                          Blue     Green                 Red

最初我已经使用pandas但是我想csv.reader在 python 中执行此操作。

这是我迄今为止的尝试:

import csv

with open('sheet1.csv', newline='') as myFile:
    reader = csv.reader(myFile)
    for row in reader:
        print(row)
4

1 回答 1

0

我知道我之前已经回答过这个问题,但我懒得去找原帖了。

[mre] 版本:

from io import StringIO
import csv
import sys

# map column names to template
mapper = lambda fieldname: fieldname.split('_')[-1]

template = '''\
1,2,3,4,5,6,7
'''

source = '''\
col_1,col_4,col_5,col_7
Yellow,Blue,Green,Red
White,Black,Cyan,Magenta
'''

fieldnames = csv.DictReader(StringIO(template)).fieldnames

out = csv.DictWriter(sys.stdout, fieldnames)
out.writeheader()

reader = csv.DictReader(StringIO(source))
for row in reader:
    out.writerow({mapper(k): v for (k, v) in row.items()})

带有实际文件版本:

import csv

# map column names to template
mapper = lambda fieldname: fieldname.split('_')[-1]

with open('template.csv', newline='') as template:
    fieldnames = csv.DictReader(template).fieldnames

with open('source.csv', newline='') as source, open('output.csv', 'w', newline='') as output:
    reader = csv.DictReader(source)

    out = csv.DictWriter(output, fieldnames)
    out.writeheader()

    for row in reader:
        out.writerow({mapper(k): v for (k, v) in row.items()})

输出:

1,2,3,4,5,6,7
Yellow,,,Blue,Green,,Red
White,,,Black,Cyan,,Magenta
于 2021-05-20T15:37:51.327 回答