首页 > 解决方案 > 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

标签: scalacsvdataframeapache-sparkapache-spark-sql

解决方案


从 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

推荐阅读