0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Databricksにてdbutils.fs.rmにより削除したdbfs上のファイルをos.path.existsで実行する際の誤検知への対応方法

Last updated at Posted at 2021-11-24

事象

Databricksにてdbutils.fs.rmにより削除したdbfs上のファイルをos.path.existsで確認すると、誤検知しました。下記画像がその際の画面であり、dbutils.fs.lsで確認するとファイルが存在しないにも関わらず、os.path.existsで確認するとTrueがリターンされてしまいました。

image.png

再現方法

src_path = '/databricks-datasets/tpch/data-001/region/region.tbl'
out_path = '/tmp/delete'
 
oup_path_for_py = '/dbfs' + out_path
 
# dbfsにコピーしたファイルを保存
dbutils.fs.cp(src_path, out_path, True)

# ファイルを削除
dbutils.fs.rm(out_path, True)

image.png

# dbutilsにてファイルの存在チェックを行う。想定は、ファイルが存在しないことによるエラーが発生
try:
    dbutils.fs.ls(out_path)
except Exception as e:
  print(e)

image.png

import os

os.path.exists(oup_path_for_py)

image.png

対応方法

情報がキャッシュされてしまうことが原因であるようで、1秒のスリープを実装することで誤検知しなくなるようです。dbutils.fs.lsを用いて存在チェックを行う方法もあるため、下記の対応方法を紹介します。

  1. sleep関数で1秒待ってから実行
  2. dbutils.fs.lsを用いた存在チェックの関数を作成

1. sleep関数で1秒待ってから実行

import time
import os

time.sleep(1)
os.path.exists(oup_path_for_py)

image.png

2. dbutils.fs.lsを用いた存在チェックの関数を作成

def fs_is(path: str):
    return_bool = True
    # dbutils.fs.lsにてエラーとなる場合に、ファイルが存在しないというリターンを返す
    try:
        file_list = dbutils.fs.ls(path)
    except:
        return_bool = False

    return return_bool


fs_is(oup_path_for_py)

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?