用于在PySpark中写入数据帧的自定义文件名

问题描述 投票:1回答:1

我想写数据框的记录。记录为json格式。因此,我需要使用自定义文件名而不是part-0000-cfhbhgh.json将内容写入文件。

json python-3.x hadoop pyspark pyspark-dataframes
1个回答
2
投票

我在scala中给出了答案,但在python中,这些也是必不可少的步骤。

 import org.apache.hadoop.fs.{FileSystem, Path}

  val fs: FileSystem = FileSystem.get(spark.sparkContext.hadoopConfiguration);
  val file = fs.globStatus(new Path("data/jsonexample/part*"))(0).getPath().getName()
  println("file name " + file)
  fs.rename(
    new Path("data/jsonexample/" + file)
    , new Path("data/jsonexample/tsuresh97_json_toberenamed.json"))

完整示例:

 import spark.implicits._

  val df = Seq(
    (123, "ITA", 1475600500, 18.0),
    (123, "ITA", 1475600500, 18.0),
    (123, "ITA", 1475600516, 19.0)
  ).toDF("Value", "Country", "Timestamp", "Sum")
  df.coalesce(1)
    .write
    .mode(SaveMode.Overwrite)
    .json("data/jsonexample/")

  import org.apache.hadoop.fs.{FileSystem, Path}

  val fs: FileSystem = FileSystem.get(spark.sparkContext.hadoopConfiguration);
  val file = fs.globStatus(new Path("data/jsonexample/part*"))(0).getPath().getName()
  println("file name " + file)
  fs.rename(
    new Path("data/jsonexample/" + file)
    , new Path("data/jsonexample/tsuresh97_json_toberenamed.json"))


结果:enter image description here

json内容:

{"Value":123,"Country":"ITA","Timestamp":1475600500,"Sum":18.0}
{"Value":123,"Country":"ITA","Timestamp":1475600500,"Sum":18.0}
{"Value":123,"Country":"ITA","Timestamp":1475600516,"Sum":19.0}

© www.soinside.com 2019 - 2024. All rights reserved.