简体   繁体   中英

Reading CSV which has Commas in a field and write the value to new csv using python/Import csv

This is my csv file which has 4 column (fields) In the second column the valus is seperated by commas. when i read this csv file using import csv (PYTHON) and write the values to other csv file its not written properly. Without comma values are fetched and written properly but not the field which contains comma in it.

DUBAI,"1st FLOOR,2nd DIV", ,65894
Gerath,"Univ, Dept",Kiev,98655
Bungy,north west, dublin,5623

Code:

with open (outputfile,"w+",newline='') as f1:
    writer = csv.writer(f1, delimiter=',')
    with open(input_csv_file,"r") as f:        
        csv_reader = csv.reader(f, delimiter=',')
        next(csv_reader) #To Skip the header files and process from 2nd rows of CSV
        for row in csv_reader:                
                name = row[0]
                address = row[1]
                city = row[2]
                postcode = row[3]
                values="{},{},{},{}".format(name,address,city,postcode)
                f1.write(values)

When the values are written to the new file it is misplaced as some fields have commas in it. If it doesnt have any comma in value it is written properly

The CSV format can process delimiters or new lines inside fields. That is what quoting is made for. But you should be consistent in reading and writing: if you use csv module for reading you should use it for writing, specialy if you can have delimiters in fields. As the double quote ( " ) is the default quoting character, and as the default quoting policy is to only quote fields requiring it, you can just let the csv module handle it:

with open (outputfile,"w+",newline='') as f1:
    writer = csv.writer(f1, delimiter=',')
    with open(input_csv_file,"r") as f:        
        csv_reader = csv.reader(f, delimiter=',')
        next(csv_reader) #To Skip the header files and process from 2nd rows of CSV
        for row in csv_reader:                
                wr.writerow(row)

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