PathNotFound错误消息:openFileForRead必须与文件而不是目录一起使用

2024-09-30 04:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下代码使用Azure databricks读取excel文件:

dfSource = spark \
  .read \
  .format("com.crealytics.spark.excel") \
  .option("Header", "true") \
  .option("inferSchema", "true") \
  .load(sSourcePath)#.withColumn("SourceFile",F.input_file_name())

但我得到的错误如下:

PathNotFound error message: openFileForRead must be used with files and not directories

当我给出完整的文件名时,Spark会正确地读取该文件

注意:我想读取文件夹中的所有文件


Tags: 文件代码comtrueformatreadazureexcel
1条回答
网友
1楼 · 发布于 2024-09-30 04:30:27

如果需要从一个目录中读取多个Excel文件,则只需迭代这些文件,将每个文件读入一个数据帧,然后合并所有这些数据帧。在DataRicks上,您可以使用dbutils.fs.ls函数列出给定目录中的文件,如下所示:

all_data = None
sSourcePath = "path_to_directory"
for f in dbutils.fs.ls(sSourcePath):
  if not f.isFile or not f.name.endswith(".xlsx"):
    continue
  df = spark \
    .read \
    .format("com.crealytics.spark.excel") \
    .option("Header", "true") \
    .option("inferSchema", "true") \
    .load(f.path)
  if all_data:
    all_data = all_data.union(df)
  else:
    all_data = df

数据帧可能在结构上不兼容,在这种情况下,您可能需要执行一些显式转换,等等

相关问题 更多 >

    热门问题