在文本文件中写入/存储数据帧

Pra*_*pad 5 scala apache-spark

我试图写dataframetext文件。如果文件包含单列,那么我可以在文本文件中写入。如果文件包含多列,那么我将面临一些错误

文本数据源仅支持单列,您有 2 列。

object replace {

  def main(args:Array[String]): Unit = {

    Logger.getLogger("org").setLevel(Level.ERROR)

    val spark = SparkSession.builder.master("local[1]").appName("Decimal Field Validation").getOrCreate()

    var sourcefile = spark.read.option("header","true").text("C:/Users/phadpa01/Desktop/inputfiles/decimalvalues.txt")

     val rowRDD = sourcefile.rdd.zipWithIndex().map(indexedRow => Row.fromSeq((indexedRow._2.toLong+1) +: indexedRow._1.toSeq)) //adding prgrefnbr               
                         //add column for prgrefnbr in schema
     val newstructure = StructType(Array(StructField("PRGREFNBR",LongType)).++(sourcefile.schema.fields))

     //create new dataframe containing prgrefnbr

     sourcefile = spark.createDataFrame(rowRDD, newstructure)
     val op= sourcefile.write.mode("overwrite").format("text").save("C:/Users/phadpa01/Desktop/op")

  }

}
Run Code Online (Sandbox Code Playgroud)

Ram*_*jan 10

您可以将数据帧转换为 rdd 并将行转换为字符串并将最后一行写为

 val op= sourcefile.rdd.map(_.toString()).saveAsTextFile("C:/Users/phadpa01/Desktop/op")
Run Code Online (Sandbox Code Playgroud)

已编辑

作为@philantrovert和@Pravinkumar都指出,上述将附加[]输出文件,这是真的。解决方案将是replace他们的empty性格

val op= sourcefile.rdd.map(_.toString().replace("[","").replace("]", "")).saveAsTextFile("C:/Users/phadpa01/Desktop/op")
Run Code Online (Sandbox Code Playgroud)

一个甚至可以使用 regex


Mar*_*ace 5

我建议使用 acsv或其他分隔格式。以下是在 Spark 2+ 中以最简洁/优雅的方式写入 .tsv 的示例

val tsvWithHeaderOptions: Map[String, String] = Map(
  ("delimiter", "\t"), // Uses "\t" delimiter instead of default ","
  ("header", "true"))  // Writes a header record with column names

df.coalesce(1)         // Writes to a single file
  .write
  .mode(SaveMode.Overwrite)
  .options(tsvWithHeaderOptions)
  .csv("output/path")
Run Code Online (Sandbox Code Playgroud)