Python csv转置

时间:2017-06-30 10:02:52

标签: python csv

我有一个csv文件,看起来像这样:

Name,A 
Age,23
DOB,26th,Jan
Anniversary,15th,May
Name,B 
Age,23
DOB,26th,Jan
Anniversary,15th,May
Name,C 
Age,23
DOB,26th,Jan
Anniversary,15th,May
Name,D 
Age,23
DOB,26th,Jan
Anniversary,15th,May

我想将第一列转换为其余数据的公共标题。我希望它看起来像这样:

Name,Age,DOB,Anniversary
A,23,26th Jan,15th May
B,23,26th Jan,15th May
C,23,26th Jan,15th May
D,23,26th Jan,15th May

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

可能的答案。

with open(file,'r') as f:
    final = []
    counter = 0
    details = []
    for line in f:
        details.append(line.split(',')[1])
        counter += 1
        if counter == 4:
            counter = 0
            final.append(details)
             details = []

现在,您可以通过final dict

来迭代该文件