1

When using pythons csv module to create a csv it is automatically putting carriage return characters at the end of strings if the string has a comma inside it e.g:

['this one will have a carriage return, at the end','this one wont']

in an excel sheet this will turn out like:

 |       |this on|

because of the extra carriage return, it will also surround the string with the comma inside in double quotes, as expected.

The code I am using is:

with open(oldfile, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for row in data:
        writer.writerow(row)

How do I create a csv using the same data format which won't have carriage returns if the strings have commas inside, I don't mind the strings being surrounded by double quotes though

Here's a link to the diagnosis of the problem with the output .csv:

Excel showing empty cells when importing file created with csv module

It's the accepted answer.

I have changed my code to:

with open(oldfile, 'w', newline='', quoting=csv.QUOTE_MINIMAL) as csvfile:
    writer = csv.writer(csvfile)
    for row in data:
        writer.writerow(row)

I am now getting the error:

TypeError: 'quoting' is an invalid keyword argument for this function
Community
  • 1
  • 1
ragardner
  • 1,836
  • 5
  • 22
  • 45

1 Answers1

2

The built-in CSV module of python has the option: csv.QUOTE_MINIMAL. When this option is added as an argument to the writer, it adds quotemarks when the delimeter is in the given string: "your text, with comma", "other field". This will eliminate the need for carriage returns. The code is:

with open(oldfile, 'w') as csvfile: writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) for row in data: writer.writerow(row)