在 Databricks 中,检查路径是否存在
In Databricks, check whether a path exist or not
我正在从数据湖存储中读取 CSV 文件,因为我有多个路径,但如果任何一个路径不存在,它就会出现异常。我想避免这种期望。
我觉得如果要检查多条路径,如果一条路径不存在,检查就会失败。也许你可以尝试不同的方法。
对于给定的示例,如果您想子选择子文件夹,您可以尝试以下操作。
读取给定目录的子目录:
# 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))
其中path
是一个特定的变量,你可以用它来检查它是否存在(scala):
dbutils.fs.ls("/mnt").map(_.name).contains(s"$path/")
我正在从数据湖存储中读取 CSV 文件,因为我有多个路径,但如果任何一个路径不存在,它就会出现异常。我想避免这种期望。
我觉得如果要检查多条路径,如果一条路径不存在,检查就会失败。也许你可以尝试不同的方法。
对于给定的示例,如果您想子选择子文件夹,您可以尝试以下操作。
读取给定目录的子目录:
# 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))
其中path
是一个特定的变量,你可以用它来检查它是否存在(scala):
dbutils.fs.ls("/mnt").map(_.name).contains(s"$path/")