我想檢查一個檔案是否存在于s3路徑中,然后將其作為 spark 資料幀讀取。問題是我不知道檔案的確切路徑,所以我必須使用通配符。例如,我的路徑如下所示:
path = 's3a://dir1/dir2/someHashString-2021-09-29-14-52-randomStuff.gz'
我無法知道什么'someHashString'或是什么'randomStuff',所以,我可能不得不使用這樣的通配符
path = 's3a://dir1/dir2/*-2021-09-29-14-52-*'
我正在嘗試這里提到的第一個解決方案,如下所示:
def path_exists(path):
# spark is a SparkSession
sc = spark.sparkContext
fs = sc._jvm.org.apache.hadoop.fs.FileSystem.get(
sc._jvm.java.net.URI.create("s3a://" path.split("/")[2]),
sc._jsc.hadoopConfiguration(),
)
return fs.exists(sc._jvm.org.apache.hadoop.fs.Path(path))
path_exists(path='s3a://dir1/dir2/*-2021-09-29-14-52-*')
但它回傳False甚至這樣的路徑確實存在。如何檢查此檔案路徑是否存在?
uj5u.com熱心網友回復:
FileSystem 方法exists不支持在檔案路徑中使用通配符來檢查是否存在。
您可以改用globStatuswhich 支持特殊模式匹配字符,例如*. 如果它回傳一個非空串列,則該檔案存在,否則它不存在:
def path_exists(path):
hpath = sc._jvm.org.apache.hadoop.fs.Path(path)
fs = hpath.getFileSystem(sc._jsc.hadoopConfiguration())
return len(fs.globStatus(hpath)) > 0
print(path_exists("s3a://dir1/dir2/*-2021-09-29-14-52-*"))
# True
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/408900.html
標籤:
