scala - Spark Dataframe 到 TXT 文件没有回车
问题描述
我正在尝试将 spark 数据框保存为文本文件。这样做时,我需要有特定的列分隔符和行分隔符。我无法让行分隔符工作。任何帮助将不胜感激。以下是供参考的示例代码。
//选项1
spark.sparkContext.hadoopConfiguration.set("textinputformat.record.delimiter", "\\§")
df.coalesce(1)
.map(_.mkString("\u00B6"))
.write
.option("encoding", "US-ASCI")
.mode(SaveMode.Overwrite).text(FileName)
//选项-2
df.coalesce(1)
.write.mode(SaveMode.Overwrite)
.format("com.databricks.spark.csv")
.option("inferSchema", "true")
.option("encoding", "US-ASCI")
.option("multiLine", false)
.option("delimiter", "\u00B6")
.option("lineSep", "\u00A7")
.csv(FileName1)
以下是我的输入和输出供参考:
输入:
Test1,Test2,Test2
Pqr,Rsu,Lmn
one,two,three
输出:
Test1¶Test2¶Test2§Pqr¶Rsu¶Lmn§one¶two¶three
解决方案
从 Spark 2.4.0 开始,“lineSep”选项可用于编写带有自定义行分隔符的 json 和文本文件(参见DataFrameWriter 规范)。此选项在以前的 Spark 版本和 csv 格式中被忽略。
val df = spark.createDataFrame(Seq(("Test1","Test2","Test2"), ("one","two","three")))
df.map(_.mkString("\u00B6"))
.coalesce(1)
.write
.option("lineSep", "\u00A7")
.text(FileName)
使用 Spark 2.4.* 输出:
Test1¶Test2¶Test2§one¶two¶three
Spark 2.3.* 及更低版本的输出(忽略“lineSep”选项):
Test1¶Test2¶Test2
one¶two¶three
推荐阅读
- mysql - mysql 5.7 是旧的吗?铁轨?
- javascript - 当我给出缩放索引时,Material-ui Popover、Select、Menus 组件位置出错
- excel - 如何将特定的 Google 电子表格转换为 Excel?
- batch-file - 批处理文件:路径上的“未定义环境变量”
- flutter - 如何使用 onGenerateRoute 在 URL 中显示 Flutter Web 路由名称?
- python - 从字符串中删除双新行
- c# - 将数据从 Ajax 传递到 ApiController
- c++ - 生成组合的虚拟按键以获得 â、ó、ć 等更复杂的字符
- ios - CocoaPods - 找不到规范
- node.js - 如何在 Google Cloud Platform 上的 Node.js 服务器上运行 Argon2?