Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python csv text manipulation

Tags:

python

csv

I want to combine combine fields from an input .csv file for output to a .csv file, and some contain commas. Here is my code, simplified

outfile = open('output.csv', 'w')

#these values are made up for this example; normally they would be read from
#a csv and passed to the following 'combine()' function

a = "John"  
b = ",Jr."  

def combine(a, b):  
    if a == "":  
        pass  #don't write anything if the field is empty
    else:  
        outfile.write(a)  
    if b =="":  
        pass  
    else:  
        outfile.write(b)  

If b starts with a comma, how do I make the output "John, Jr." ? I have tried using the csv.writer writerow() but it puts a comma delimiter between each character. I have tried defining an escapechar but it just outputs "John \" , "Jr." Suggestions?

like image 774
Brandon Dorris Avatar asked Jul 14 '26 01:07

Brandon Dorris


2 Answers

If you would like to know details about CSV, there is a spec: https://www.rfc-editor.org/rfc/rfc4180

In general it states the following "Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes."

"If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote."

Implementations like Excel always put all field values into double quotes.

If you open a file for read or write you can specify the type of quoting directly

mcvs = csv.writer(open('file.csv', 'wb'), quoting=csv.QUOTE_ALL)

will always add quotes to the around the field value.

For all possible values look at the python documentation

http://docs.python.org/library/csv.html#module-csv

like image 172
sebs Avatar answered Jul 17 '26 16:07

sebs


csv.writer allows you to add a quoting keyword which can be used to control how things are quoted.

You probably want something like csv.QUOTE_MINIMAL.

>>> import csv
>>> with open('eggs.csv', 'wb') as outfile:
...     writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL)
...     writer.writerow(['Spam'] * 5 + ['Baked Beans'])
...     writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
like image 20
Tim McNamara Avatar answered Jul 17 '26 17:07

Tim McNamara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!