简体   繁体   中英

Python: Reformat CSV file

I have a CSV file like this:

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

Whenever there's a 0 in column 2 (like the 0 after gender and Additional),I'd like to start reformating it to something like this:

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

How do I do that? I appreciate any help on this.

file.csv

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

code

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM