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

Pyspark 在Spark中,如果数据帧中没有行,如何在文件中写入头?,pyspark,header,apache-spark-sql,writing,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)

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

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');

我想要文件中的头行,即使数据帧中没有数据行。

如果只想要头文件。您可以使用fold left创建每个带有空白的列,并将其另存为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()
}

我和你有同样的问题,在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)

我希望spark的一些内置功能可以做到这一点。打印空数据帧不是spark的标准做法。无论如何,如果你能找到一些正在构建的东西,请与我分享。
# 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)