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

时间:2019-07-09 06:38:25

标签: pyspark header apache-spark-sql writing

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

I am writing dataframe using these setting and command:
Dataframe.repartition(1) \
         .write \
         .format("com.databricks.spark.csv") \
         .option("ignoreLeadingWhiteSpace", False) \
         .option("ignoreTrailingWhiteSpace", False) \
         .option("header", "true") \
         .save('/mnt/Bilal/Dataframe');

即使数据帧中没有数据行,我也希望文件中的标题行。

2 个答案:

答案 0 :(得分:1)

如果只想包含头文件。您可以使用向左折创建具有空白的每一列,并将其另存为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)

答案 1 :(得分:0)

我在 Pyspark 中遇到了同样的问题。当数据帧为空时(例如,在.filter()转换之后),则输出为一个没有标题的空csv。

因此,我创建了一个自定义方法,用于检查输出CSV是否为一个空CSV 。如果是,则仅添加标题。

import glob
import csv

def add_header_in_one_empty_csv(exported_path, columns):
    list_of_csv_files = glob.glob(os.path.join(exported_path, '*.csv'))
    if len(list_of_csv_files) == 1:
        csv_file = list_of_csv_files[0]
        with open(csv_file, 'a') as f:
            if f.readline() == b'':
                header = ','.join(columns)
                f.write(header)

示例:

# Create a dummy Dataframe
df = spark.createDataFrame([(1,2), (1, 4), (3, 2), (1, 4)], ("a", "b"))

# Filter in order to create an empty Dataframe
filtered_df = df.filter(df['a']>10)

# Write the df without rows and no header
filtered_df.write.csv('output.csv', header='true')

# Add the header
add_header_in_one_empty_csv('output.csv', filtered_df.columns)