You need to enable JavaScript to run this app. Pyspark如何将DataFrame保存为指定名称的单JSON文件而非分区文件
优惠活动
大模型
产品
解决方案
定价
更多

Pyspark如何将DataFrame保存为指定名称的单JSON文件而非分区文件

PySpark 导出DataFrame为单个指定名称JSON文件的解决方案

问题原因

Spark原生的DataFrame写入API设计为将指定路径作为输出目录,无论分区数多少,都会在该目录下生成对应分区的part-前缀数据文件,因此直接调用save()方法无法直接生成指定名称的单个文件。

解决方案

方案1:小数据量场景,转Pandas导出(最简单)

如果DataFrame数据量不大,可全部加载到Driver内存,直接转Pandas后调用其JSON导出方法即可:

df_3.toPandas().to_json(filename, orient='records', force_ascii=False)

参数说明:orient='records'会输出和Spark JSON导出格式一致的行级JSON结构,force_ascii=False可避免中文乱码,可根据需求调整

方案2:大数据量场景,先写临时目录再重命名

如果数据量较大,不能全量加载到Driver内存,可先按原有逻辑写入临时目录,再将生成的part文件重命名为目标文件,最后清理临时目录:

本地文件系统环境代码:

import os
import shutil

# 自定义临时目录名
temp_dir = "tmp_json_temp_output"
# 先将数据写入临时目录
df_3.coalesce(1).write.format('json').mode('overwrite').save(temp_dir)

# 遍历找到分区文件
for f_name in os.listdir(temp_dir):
    if f_name.startswith("part-"):
        # 移动重命名为目标文件
        shutil.move(os.path.join(temp_dir, f_name), filename)
        break
# 清理临时目录
shutil.rmtree(temp_dir)

HDFS环境代码:

from py4j.java_gateway import java_import

temp_dir = "tmp_json_temp_output"
df_3.coalesce(1).write.format('json').mode('overwrite').save(temp_dir)

# 获取Hadoop文件系统实例
hadoop_conf = sc._jsc.hadoopConfiguration()
fs = sc._jvm.org.apache.hadoop.fs.FileSystem.get(hadoop_conf)
java_import(sc._jvm, "org.apache.hadoop.fs.Path")

# 匹配part开头的分区文件
part_file = fs.globStatus(sc._jvm.Path(f"{temp_dir}/part-*"))[0].getPath()
# 重命名为目标文件
fs.rename(part_file, sc._jvm.Path(filename))
# 清理临时目录
fs.delete(sc._jvm.Path(temp_dir), True)

注意事项

  • coalesce(1)会将全量数据集中到一个分区处理,仅适合数据量不大的场景,超大数据量不建议强行导出为单个文件,会导致Driver节点内存溢出、任务执行过慢等问题。

内容的提问来源于stack exchange,提问作者Young

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 14:39:03