在 Spark 中,如果数据帧中没有行,如何在文件中写入标头?

2024-01-15

如果数据框中没有行,我想在文件中写入标题,当前当我将空数据框写入文件时,会创建文件,但其中没有标题。

我正在使用这些设置和命令编写数据帧:

Dataframe.repartition(1) \
        .write \
        .format("com.databricks.spark.csv") \
        .option("ignoreLeadingWhiteSpace", False) \
        .option("ignoreTrailingWhiteSpace", False) \
        .option("header", "true") \
        .save('/mnt/Bilal/Dataframe');

我想要文件中的标题行,即使数据框中没有数据行。


如果你只想有头文件。您可以使用左折叠创建带有空白的每一列并将其保存为 csv。我没有使用过 pyspark,但这就是在 scala 中完成的方法。大部分代码应该是可重用的,您只需将其转换为 pyspark

val path ="/user/test"
val newdf=df.columns.foldleft(df){(tempdf,cols)=>
tempdf.withColumn(cols, lit(""))}

创建一个写入头文件的方法

 def createHeaderFile(headerFilePath: String, colNames: Array[String]) {

//format header file path
val fileName = "yourfileName.csv"
val headerFileFullName = "%s/%s".format(headerFilePath, fileName)

    val hadoopConfig = new Configuration()
val fileSystem = FileSystem.get(hadoopConfig)
val output = fileSystem.create(new Path(headerFileFullName))
val writer = new PrintWriter(output)

for (h <- colNames) {
  writer.write(h + ",")
}
writer.write("\n")
writer.close()
}

在你的 DF 上调用它

 createHeaderFile(path, newdf.columns)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Spark 中,如果数据帧中没有行,如何在文件中写入标头? 的相关文章

随机推荐