Spark结合Pandas导出Excel提示执行成功但目标路径找不到文件的问题求助
Spark结合Pandas导出Excel提示执行成功但目标路径找不到文件的问题求助
我刚在学习Python,尝试把从Spark SQL查询到的记录导出到Excel文件里,以下是我运行的代码:
# Install the openpyxl module #%pip install openpyxl # Import pandas import pandas as pd import os df = spark.sql(""" select distinct BILLING_ACCOUNT_NUMBER from prd_pdt_general_scm.scm_core.subscriber_soc where SOC_CODE='P360HT' and SUBSCRIBER_NUMBER ='0000000000' and curr_ind='Y' """) #display(df) # this is showing the results correctly. # Convert the Spark DataFrame to a Pandas DataFrame pandas_df = df.toPandas() # Define the directory and file path directory = r'C:/Users/achatte17/Documents/ISE' excel_file_path = os.path.join(directory, 'output.xlsx') display(excel_file_path) #Also showing the path correctly # Create the directory if it does not exist os.makedirs(directory, exist_ok=True) # Save the DataFrame to an Excel file writer = pd.ExcelWriter(excel_file_path) pandas_df.to_excel(writer, index = False) writer.save() writer.close() # Get the absolute path file_path = os.path.abspath('output.xlsx') # Print the file location print(f'The location of the Excel file is: {file_path}') #this is showing a different path as /home/spark-d377ec0c-caf2-4f42-9dc7-34/output.xlsx
我试过多种方式指定目录,也换了不同的导出写法,代码执行时没有任何报错,但就是找不到生成的Excel文件。更奇怪的是,最后打印的文件路径显示的是/home/spark-d377ec0c-caf2-4f42-9dc7-34/output.xlsx,这和我一开始指定的本地C盘路径完全不一样。
问题原因分析
你现在运行代码的环境应该是远程Spark集群(比如Databricks这类云Spark平台),这个环境部署在远程服务器上,和你本地的Windows电脑是完全独立的两个机器:
- 你指定的
C:/Users/achatte17/Documents/ISE是本地电脑的路径,但远程Spark集群的服务器根本无法访问到你本地的C盘,所以代码并没有把文件写到你期望的本地路径。 - 最后打印的
/home/...路径是远程Spark集群服务器的默认工作目录,文件其实生成在这个远程路径里,只是你在本地电脑看不到。
解决办法
根据你的需求,有两种常见的处理方式:
1. 先写到集群文件系统,再下载到本地(适合云Spark环境)
如果是在Databricks这类云Spark平台,推荐先把文件写到集群的分布式文件系统(比如DBFS),再通过平台UI下载到本地:
# 修改路径为DBFS路径 directory = '/dbfs/FileStore/ISE' excel_file_path = os.path.join(directory, 'output.xlsx') # 后续保存代码不变... # 保存完成后,可在Databricks UI的「Data > DBFS > FileStore > ISE」找到文件,点击下载到本地
2. 在本地Python环境运行代码(直接写入本地C盘)
如果想直接把文件写到本地C盘,需要在自己的Windows电脑上搭建本地PySpark环境,然后在本地运行这段代码。这样代码就能直接访问本地C盘,文件会生成在你指定的位置。
3. 修正路径打印的小问题
你最后用os.path.abspath('output.xlsx')获取的是集群工作目录的绝对路径,会出现偏差。应该直接用之前定义好的excel_file_path来打印正确路径:
print(f'The location of the Excel file is: {excel_file_path}')
备注:内容来源于stack exchange,提问作者Anomitra
相关产品推荐
相关产品推荐

