tags:

views:

402

answers:

3

I hava a CSV file that I want to treat as source code. Essentially I want to take the csv lines and use them as if they were calls to a function with all string parameters.

The problem is, the individual elements are only double quoted when there is a comma in the text.

Is there a quick way of adding the double quotes all elements in a csv row.

The original document is an excel file so anything in excel would be fine, but other quick tools would be welcome.

+1  A: 

Try the following Python script, just for fun.
It adds quotes to strings in the CSV that don't have them already.

This is a really simple approach - you will likely find corner cases that don't work for you (strings with embedded quotes and commas?). Fix it!

(oh, this can be written in far less lines of code, I know. Not the point here).

import sys
import re

def addQuotes( str ):
    matches = re.match( '^".*"$', str )
    if matches == None:
        return '"' + str + '"'
    return str

# Iterate over standard input. NOTE - this isn't line-buffered, don't try using
# this script interactively...
for line in sys.stdin:

    # Remove trailing linefeed.
    line = line.strip()

    # Split the line into parts separated by commas.
    parts = line.split( ',' )

    # Add quotes to each part that doesn't have quotes already.
    newParts = map( addQuotes, parts )

    # Concatenate the parts back to a single line.
    concatParts = ','.join( newParts )

    # And print it.
    print concatParts

Pipe the CSV file to this, using something like -

 python QuoteCSV.py < input.csv
Hexagon
A: 

Can you change your output to use a different field separator? Ideally you could use something that would never be used in a field value - then it's a simple search & replace problem.

Another option would be to import the CSV into a SQL table and then dump it back out with quotes around all the fields.

dm0527
+1  A: 

Have a look at the Excel CONCATENATE() function. It takes a comma delimitted list of strings or quoted literals...

e.g. CONCATENATE("""", A1, """") etc.

where A1 is one of your columns.

I frequently do this for one-off SQL inserts, so where you use double-quotes, I write SQL insert statements

Neil Fenwick