json - 自定义文件名以在PySpark中写入数据框

标签 json python-3.x hadoop pyspark pyspark-dataframes

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

最佳答案

我在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}

关于json - 自定义文件名以在PySpark中写入数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61413911/

相关文章:

javascript - 检查数组对象中的输出是否有 'error' 并在 'error' 中显示消息

node.js - npm 命令不更新 json

python - 如何制作分割窗口?

hadoop - 是否可以在 hadoop 中将映射器的一部分发送到 reducer,而仅将另一部分写入 HDFS?

json - "Failed to invoke public scala.collection.immutable.List() with no args"使用 GSON

java - 编辑从解析的 JSON 字符串中检索到的字符串

python - 透视/取消堆叠具有重复条目的 DataFrame,无需聚合

python-3.x - 在 Visual Studio Code 中安装 pip 后如何重新加载 python 包?

algorithm - MapReduce 替代品

hadoop - Hive 不会写入 aws s3