apache-spark - 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)
解决方案
如果您知道包含换行符的字段,则可以在字段值周围添加引号,然后写入 csv。
from pyspark.sql import functions as F
df = df.select(field1,concat(F.lit('\"'),field2,F.lit('\"')),field3)
推荐阅读
- sql - SQL 根据其他行的值更新每一行
- css - 字体出现锯齿状,抗锯齿更接近淡紫色而不是灰色
- oauth - 通过 Azure API 管理公开受 OAUTH 保护的 API 并执行委派
- git - 如何在不影响之前完成的拉取请求的情况下将分叉的 repo 重置为其原始状态?
- c# - 当重复选择文件或Excel格式的文件时,会抛出此异常
- html - 将文本对齐到全宽和相等的自动间距
- ionic3 - 无法在 android 应用程序上调用 api,但它可以在浏览器上运行
- java - Retrieving data from httpURLConnection with a listener
- visual-studio-extensions - 是否可以使用 SDK 风格的项目编写 VS 扩展?
- react-native - React-Native 在 TextInput 中一起调整表情符号和文本大小