Escape Double Quotes When Writing CSV in Spark
How Spark's CSV writer handles embedded double quotes, why its default backslash escaping can break other parsers, and when to switch to doubled quotes.
When a Spark DataFrame contains text with double quotes, the CSV writer has to encode those quotes so that a parser can tell where a field ends. Spark's default way of doing this differs from the convention many other tools expect. This review explains what the escaping options change, when the default is acceptable, and when you should configure Spark to double the quotes instead.
Short recommendation
If the CSV will be read by anything other than Spark, set the escape character to a double quote so embedded quotes are written as two consecutive quotes. That is the convention described in RFC 4180, the most widely cited CSV specification. The main benefit is interoperability: parsers that follow that convention will reconstruct the original text correctly. The decisive tradeoff is that Spark's reader uses the same backslash default as its writer, so files written with doubled quotes must also be read back with the escape option set to a double quote. If the files only ever move between Spark jobs that share the same settings, the default backslash escaping works and changing it gains little.
Plain, unquoted text is preferable only when you control the data and can guarantee it contains no quote characters, delimiters or line breaks. In that case no escaping is triggered and the question does not arise. For a format where quoting rules matter less, a delimited file with a delimiter that never appears in the data, or a typed format such as Parquet, avoids the problem entirely.
What the escaping options actually change
Escaping in this context changes the stored characters in the output file. It is not a visual effect, a font or a display setting; the bytes written to disk are different. The original value is unchanged in the DataFrame, and a correctly configured reader restores it exactly.
Spark's CSV data source documents several options that interact here. Defaults below are as described in the Spark documentation; confirm them against the documentation for the Spark version you run, since this review was not supplied with version-specific evidence.
| Option | Documented default | Effect when writing |
| quote | double quote | Character used to enclose fields that need quoting. |
| escape | backslash | Character placed before a quote that appears inside a quoted field. |
| escapeQuotes | true | Values that contain a quote character are enclosed in quotes. |
| quoteAll | false | When true, every field is enclosed in quotes, not only those that need it. |
| charToEscapeQuoteEscaping | backslash when escape and quote differ, otherwise none | Character used to escape the escape character itself when it precedes a quote. |
With the defaults, a value such as She said "hi" is enclosed in quotes and each inner quote is preceded by a backslash. Setting escape to a double quote makes Spark write each inner quote twice instead. The illustrative input and expected outputs below follow directly from the documented behavior of these options; they are not results from a test run supplied with this brief.
Input value: She said "hi"
Default (escape = \): "She said \"hi\""
escape = " "She said ""hi"""
The second form is the one RFC 4180 describes: inside a quoted field, a literal quote is represented by two quotes. The backslash form is a common convention in other systems but is not part of that specification.
How to configure it
Set the escape option on the writer. Setting quote explicitly is optional because a double quote is already the default, but it makes the intent clear to anyone reading the job.
# PySpark
(df.write
.option("header", True)
.option("quote", '"')
.option("escape", '"')
.mode("overwrite")
.csv(output_path))
// Scala
df.write
.option("header", "true")
.option("quote", "\"")
.option("escape", "\"")
.mode("overwrite")
.csv(outputPath)
When reading those files back into Spark, apply the same escape setting. If the data contains line breaks inside fields, also enable multiLine on the reader, because Spark otherwise treats each physical line as a record.
# PySpark
df2 = (spark.read
.option("header", True)
.option("quote", '"')
.option("escape", '"')
.option("multiLine", True)
.csv(output_path))
Will the output stay usable after it leaves Spark?
Usability depends on whether the escaping convention in the file matches the one the receiving parser expects. A mismatch does not usually raise an error; it silently produces wrong values.
- Reader expects doubled quotes, file uses backslashes: the backslash is kept as a literal character, and the quote after it may be read as the end of the field, which can shift following columns.
- Reader expects backslashes, file uses doubled quotes: a pair of quotes may be interpreted as the field closing and immediately reopening, again risking split or merged values.
- Backslashes that are genuine data: under the default settings, a backslash that appears just before a quote in the source text interacts with the escape rules. Switching escape to a double quote removes this ambiguity, because backslashes then have no special meaning.
No tests of specific destinations, such as particular spreadsheet applications, databases or import tools, were supplied for this review, so no claim is made about how any named product handles either convention. Before relying on a destination, write a small sample containing quotes, commas, backslashes and line breaks, load it there, and compare the values field by field with the source.
Copying and pasting raw CSV text carries the escape characters along with it. Someone reading the file in a text editor will see the extra quotes or backslashes, which is expected and does not indicate corruption. If people rather than parsers are the intended audience, provide the data in its parsed form, such as a rendered table, instead of asking readers to interpret escaped text.
Accessibility and reading order are not affected in the way they are by visual text effects. The escaping exists only in the file encoding; once a parser decodes it, assistive technology and search see the original characters. The accessibility concern arises only if escaped raw text is shown directly to readers, where screen readers may announce the extra symbols.
Checks before you commit to a setting
- Identify every consumer of the files and the escaping convention each one expects.
- Use the same quote and escape settings on the Spark writer and any Spark reader.
- Enable multiLine on read if fields can contain line breaks.
- Round-trip a sample with awkward values and compare it with the source data.
- Record the chosen options alongside the output so later consumers know how to parse it.
Known gaps
This review relies on the documented behavior of Spark's CSV options and the RFC 4180 convention. It does not include measured output from a specific Spark version or tested results from any downstream tool, so defaults and edge-case handling should be confirmed in your own environment.