在Databricks中,检查路径是否存在

问题描述 投票:0回答:4

我正在从数据湖存储中读取 CSV 文件,因为我有多个路径,但如果任何一个路径不存在,则会出现异常。我想避免这种期望。

csv exception path load databricks
4个回答
3
投票

我认为如果你想检查多条路径,如果一条路径不存在,检查就会失败。也许你可以尝试不同的方法。

对于给定的示例,如果您想子选择子文件夹,您可以尝试以下操作。

读取给定目录的子目录:

# list all subfolders and files in directory demo
dir = dbutils.fs.ls ("/mnt/adls2/demo")

过滤掉相关子目录:

pathes = ''

for i in range (0, len(dir)):
  subpath = dir[i].path
  if '/corr' in subpath or '/deci' in subpath and subpath.startswith ('dbfs:/'): # select dirs to read 
    pathes =  pathes + (dir[i].path) + ' '  

# convert the string to a list 
pathes = list(pathes.split())

使用结果列表读取数据帧:

df = (spark.read
  .json(pathes))

0
投票

其中

path
是一个特定变量,您可以使用它来检查它是否存在(scala):

dbutils.fs.ls("/mnt").map(_.name).contains(s"$path/")

0
投票

您可以通过运行下面的代码片段来完成此操作,该代码片段使用新的 databricks python SDK:

安装包:

pip install databricks-sdk

Python 片段:

from databricks.sdk import WorkspaceClient

# Remember to change the arguments below
w_client = WorkspaceClient(host="my_host", token="my_db_tokens")

# add an absolute path
dbfs_path_exist = w_client.dbfs.exists('/dbfs_my_path')

希望有帮助:)


-2
投票

您必须使用块 blob 作为装载点才能从数据块中工作并能够看到其中的 blob。

© www.soinside.com 2019 - 2024. All rights reserved.