如何在单个 csv 文件中保存 pyspark 数据框 [英] How to save pyspark data frame in a single csv file
问题描述
这是如何将数据帧保存到 csv pyspark 线程.
我正在尝试将我的 pyspark 数据框 df 保存在我的 pyspark 3.0.1 中.所以我写了
I'm trying to save my pyspark data frame df in my pyspark 3.0.1. So I wrote
df.coalesce(1).write.csv('mypath/df.csv)
但执行此操作后,我在 mypath 中看到一个名为 df.csv 的文件夹,其中包含以下 4 个文件
But after executing this, I'm seeing a folder named df.csv in mypath which contains 4 following files
1._committed_..
2._started_...
3._Success
4. part-00000-.. .csv
你能告诉我如何将所有数据保存在 df.csv
中吗?
Can you suggest to me how do I save all data in df.csv
?
推荐答案
您可以使用 repartition(1)
将文件保存在 1 个 csv 分区中,然后重命名此 csv 并将其移动到所需的文件夹.
You can use repartition(1)
to save the file in just 1 csv partition, then rename this csv and move it to the desired folder.
这是一个执行此操作的函数:
Here is a function that does that:
df
:你的 dffileName
:您要为 csv 文件命名的名称filePath
:要保存到的文件夹
df
: Your df
fileName
: Name you want to for the csv file
filePath
: Folder where you want to save to
def export_csv(df, fileName, filePath):
filePathDestTemp = filePath + ".dir/"
df\
.repartition(1)\
.write\
.save(filePathDestTemp)
listFiles = dbutils.fs.ls(filePathDestTemp)
for subFiles in listFiles:
if subFiles.name[-4:] == ".csv":
dbutils.fs.cp (filePathDestTemp + subFiles.name, filePath + fileName+ '.csv')
dbutils.fs.rm(filePathDestTemp, recurse=True)
这篇关于如何在单个 csv 文件中保存 pyspark 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!