首页 > 解决方案 > pyspark csv write:双引号中带有换行符的字段

问题描述

我正在使用以下选项将 spark 数据帧写入 csv:

     df
     .repartition("col1")
     .write
     .partitionBy("col1")
     .option("header", "true")
     .option("quote", "\"")
     .option("escape", "\"")
     .option("emptyValue", "")
     .option("ignoreLeadingWhiteSpace", False)
     .option("ignoreTrailingWhiteSpace", False)
     .option("maxRecordsPerFile", 100000)
     .csv("some_path")

我的数据框中的几个字符串列包含换行符。我希望所有包含新行的字段都用". 我找不到在火花中做到这一点的方法。我知道我可以用.option("quoteAll", True)引号括住所有字段,但我想避免这样做。

这是一个数据示例

实际的:

field1, field2, field3
101, field with new line char at the end
, false
102, field with new line char at the end
, false

预期的:

field1, field2, field3
101, "field with new line char at the end
",another field
102, "field with new line char at the end
",another field

编辑 1:数据中的换行符是\r(ascii 值 13)

标签: apache-sparkpysparkapache-spark-sql

解决方案


如果您知道包含换行符的字段,则可以在字段值周围添加引号,然后写入 csv。

from pyspark.sql import functions as F

df = df.select(field1,concat(F.lit('\"'),field2,F.lit('\"')),field3)

推荐阅读