-1

我有一个这样的 CSV 文件:

Additional,0        
No     1284         
Yes      44 
Total count,1286
gender,0        
Female    918           
Male      904           
Total count,1822

每当第 2 列中有 0 时(如性别和附加后的 0),我想开始将其重新格式化为如下内容:

Additional,1286     
No,1284         
Yes,44 
gender,1822     
Female,918          
Male,904    

我怎么做?我很感激这方面的任何帮助。

4

1 回答 1

1

文件.csv

Additional,0        
No,1284         
Yes,44 
Total count,1286
gender,0        
Female,918           
Male,904           
Total count,1822

代码

import csv

with open('file.csv', 'rb') as csvread:
    reader = csv.reader(csvread)
    with open('out.csv', 'wb') as csvwrite:
        writer = csv.writer(csvwrite)
        for row in reader:
            frow = []
            for i, val in enumerate(row):
                val = val.strip()
                if val.isdigit():
                    val = int(val)
                if i == 1 and val == 0:
                    if frow[0] == 'Additional':
                         val = 'something'
                    elif frow[0] == 'gender':
                         val = 'something else'
                frow.append(val)
            writer.writerow(frow)
于 2015-09-10T18:14:20.153 回答