簡體   English   中英

使用 spark 和 python adls gen 2 僅列出子文件夾名稱

[英]List only the subfolder names using spark and python adls gen 2

我有一個文件夾結構,其中有源、年、月、日,然后是鑲木地板文件,在這里我每天將數據存儲在一個新文件夾中。

來源

  • 2022年
    • 12
      • 30
      • 31
  • 2023年
    • 01
      • 01
      • 02
      • 03

等等。

我需要動態地能夠 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM