Python:格式化CSV文件



我有一个像这样的CSV文件:

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

无论何时在第二列有一个0(就像在gender和Additional后面的0),我想开始将它重新格式化为这样的东西:

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

我该怎么做?

file.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)

相关内容

  • 没有找到相关文章

最新更新