[英]Read files from multiple folders from ADLS gen2 storage via databricks and create single target file
[英]How to create directory in ADLS gen2 from pyspark databricks
摘要:我正在處理一個用例,我想在數據塊中的 pyspark 流作業中通過 ADLS 中的 cv2 寫入圖像,但是如果該目錄不存在,它就不起作用。 但我想根據圖像屬性以特定結構存儲圖像。 所以基本上我需要在運行時檢查目錄是否存在,如果不存在則創建它。 最初我嘗試使用 dbutils,但 dbutils 不能在 pyspark api 中使用。https://github.com/MicrosoftDocs/azure-docs/issues/28070
預期結果:能夠在運行時從 ADLS Gen2 中的 pyspark 流作業中創建目錄。
可重現的代碼:
# Read images in batch for simplicity
df = spark.read.format('binaryFile').option('recursiveLookUp',True).option("pathGlobfilter", "*.jpg").load(path_to_source')
# Get necessary columns
df = df.withColumn('ingestion_timestamp',F.current_timestamp())
.withColumn('source_ingestion_date',F.to_date(F.split('path','/')[10]))
.withColumn('source_image_path',F.regexp_replace(F.col('path'),'dbfs:','/dbfs/')
.withColumn('source_image_time',F.substring(F.split('path','/')[12],0,8))
.withColumn('year', F.date_format(F.to_date(F.col('source_ingestion_date')),'yyyy'))
.withColumn('month', F.date_format(F.to_date(F.col('source_ingestion_date')),'MM'))
.withColumn('day', F.date_format(F.to_date(F.col('source_ingestion_date')),'dd'))
.withColumn('base_path', F.concat(F.lit('/dbfs/mnt/development/testing/'),F.lit('/year='),F.col('year'),
F.lit('/month='),F.col('month'),
F.lit('/day='),F.col('day'))
# function to be called in foreach call
def processRow(row):
source_image_path = row['source_image_path']
base_path = row['base_path']
source_image_time = row['source_image_time']
if not CheckPathExists(base_path):
dbutils.fs.mkdirs(base_path)
full_path = f"{base_path}/{source_image_time}.jpg"
im = image=cv2.imread(source_image_path)
cv2.imwrite(full_path,im)
# This fails
df.foreach(processRow)
# Due to below code block
if not CheckPathExists(base_path):
dbutils.fs.mkdirs(base_path)
full_path = f"{base_path}/{source_image_time}.jpg"
im = image=cv2.imread(source_image_path)
cv2.imwrite(full_path,im)
有人有什么建議嗎?
據我所知, dbutils.fs.mkdirs dbutils.fs.mkdirs(base_path)
適用於dbfs:/mnt/mount_point/folder
之類的路徑。
我已經復制了這個,當我使用mkdirs
function 檢查/dbfs/mnt/mount_point/folder
之類的路徑時,該文件夾沒有在 ADLS 中創建,即使它在 databricks 中給了我True
。
但是對於dbfs:/mnt/mount_point/folder
它工作正常。
這可能是這里的問題。 因此,首先使用此路徑/dbfs/mnt/mount_point/folder
檢查路徑是否存在,如果不存在,則使用dbfs:/
此路徑創建目錄。
例子:
import os
base_path="/dbfs/mnt/data/folder1"
print("before : ",os.path.exists(base_path))
if not os.path.exists(base_path):
base_path2="dbfs:"+base_path[5:]
dbutils.fs.mkdirs(base_path2)
print("after : ",os.path.exists(base_path))
您可以看到文件夾已創建。
如果您不想直接使用os
,請使用以下列表檢查路徑是否存在並創建目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.