[英]SAS token using Azure AD Service Principle for ADLS Gen2 at directory level in java
[英]List only the subfolder names using spark and python adls gen 2
我有一个文件夹结构,其中有源、年、月、日,然后是镶木地板文件,在这里我每天将数据存储在一个新文件夹中。
来源
等等。
我需要动态地能够 select 最新的文件夹。 在这种情况下,它是文件夹 2023/01/03,但我似乎无法将其取出。
我尝试导入 os 并使用以下代码:
pq_date_folders = f'{abfss_path}/{var_table}/.'
for root, dirs, files in os.walk(pq_date_folders, topdown=False):
for name in dirs:
print(os.path.join(root, name))
但是什么也没有打印出来。 我究竟做错了什么?
数据存储在 adls gen 2 中,使用 python 通过数据块查询。
问题是你使用os库来做到这一点,databricks 集群和 datalake 在不同的machines.networks中,databricks 使用凭据连接到 datalake 以获取数据,你需要将这些凭据传递给你想要的任何操作对这些数据执行操作,幸运的是,这些凭据存在于您的 spark session 中,因此您可以使用 hadoop 和 spark session 配置来查询数据湖中的数据:
我实现了一个 function 来获取目录下的最大路径,当我们获取最大路径时 w 检查它的子目录,然后我们再次获取最大路径等等(在 Azure databricks 上使用数据湖 adls gen2 进行了测试):
# First make sure to install hdfs library:
!pip install hdfs
然后:
# Function to get the max directory under a path:
def getLastPath(path, fs):
pathsList = list(map(lambda x: str(x.getPath()),fs.listStatus(Path(path))))
return sorted(pathsList)[-1]
然后像这样使用它到包含文件夹 2022、2023... 的根路径:
path = "dbfs:/mnt/xxx-dls/root_path/"
Path = spark.sparkContext._gateway.jvm.org.apache.hadoop.fs.Path
fs = Path(path).getFileSystem(sc._jsc.hadoopConfiguration())
while fs.isDirectory(Path(getLastPath(path, fs))):
path = getLastPath(path, fs)
print(path)
如果您只使用数据块,另一种选择是使用 dbutilis.fs.ls("/path/..") 并获取每个目录中的最大文件夹。
最后使用 OneCricketeer 的以下链接:
https://github.com/Azure/azure-data-lake-store-python
下面的代码给了我路径,我可以从中提取名称:
folder = dbutils.fs.ls(path)
当您在 pyspark 中执行此操作时,您可以使用以下替代方法,也可以使用glob
。
为此,首先需要将 ADLS 安装到数据块。
这些是我在存储中的文件夹:
在这里,我每天将数据存储在一个新文件夹中。
如果你每天存储数据(每天创建新文件夹),那么你可以像下面那样做。
import glob, os
import datetime
#if your folder creation and file uploading done on day to day basis
latest_date =datetime.datetime.today().strftime('%Y/%m/%d')
print("Latest_date : ",latest_date)
for x in glob.iglob('/dbfs/mnt/data/**',recursive=True):
if latest_date in x:
print(x)
如果您的文件夹创建是定期完成的,例如 10 天,那么您可以像下面那样做。
import glob, os
import datetime
#if your folder creation and file uploading done on 10 day basis
d = datetime.datetime.today()
dates_list = [(d - datetime.timedelta(days=x)).strftime('%Y/%m/%d') for x in range(10)]
print("Last 10 days for sample : ",dates_list)
for x in date_list:
for y in glob.iglob('/dbfs/mnt/data/**',recursive=True):
if x in y:
print(y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.