2017-06-14 45 views
1

我正在嘗試將dataframe寫入text文件。如果一個文件包含單列,那麼我可以寫入文本文件。如果文件包含多列,那麼我面臨一些錯誤在文本文件中寫入/存儲數據幀

文本數據源僅支持單列,並且您有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") 

    } 

} 

回答

2

找到可以轉換數據幀到RDD和隱蔽該行字符串,並寫最後行

val op= sourcefile.rdd.map(_.toString()).saveAsTextFile("C:/Users/phadpa01/Desktop/op") 

編輯

由於@philantrovert和@Pravinkumar指出,上述內容將附加[]在輸出文件中,這是真的。該解決方案將是replace他們empty字符作爲

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

甚至可以使用regex

+0

我認爲這會在每行的兩端添加'['和']''。 – philantrovert

+0

,但它爲每條記錄添加了「[]」每條記錄.eg:[2,12.2,12.2] –

+0

是的,它可以替換爲空。讓我更新答案 –

0

可以保存爲文本CSV文件(.format("csv")

其結果將是在CSV格式的文本文件中,每個列將一個逗號分隔。

val op = sourcefile.write.mode("overwrite").format("csv").save("C:/Users/phadpa01/Desktop/op") 

更多信息可以在spark programming guide

+0

我想要的文件擴展名應該由上述方案的文件擴展名是.txt是的.csv –

+0

你怎麼想每行要打印?逗號分隔或其他東西? – stefanobaghino

+0

@PravinkumarHadpad - 你爲什麼在意輸出文件擴展名是.txt還是.csv? – Yaron

0

我用databricks API來我的DF輸出保存到文本文件。

myDF.write.format("com.databricks.spark.csv").option("header", "true").save("output.csv") 
2

我會建議使用csv或其他分隔格式。以下是最簡潔/優雅方式爲例來寫星火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") 
相關問題