LoginSignup
7
5

More than 5 years have passed since last update.

[ や ] を含むファイルがglob.glob()で列挙されない問題の解決法

Last updated at Posted at 2014-07-02

glob.glob()でつまずいたので、メモ。

現象

glob.glob() だと、[ ]を含むパスが取得できない。

glob.glob(r"d:\test\[1].*") 
#=> [1].txt にマッチしない
glob.glob(r"d:\test\\[1\].*") # \[ \] と書いてもダメ 

解決方法

  1. パスマスクを以下のようにエスケープする
[ -> [[]
] -> []]
glob.glob(r"d:\test\[[]1[]].*") 
#=> [1].txt にマッチする

glob.glob() の代わりに以下の関数を使うもよし。

def escapeBraceForGlob(str):
    '''
    convert [ -> [[]  ,  ] -> []]
    '''
    newStr = str.replace("[","\\[").replace("]","\\]")
    newStr = newStr.replace("\\[","[[]").replace("\\]","[]]")
    return newStr


def globEscapeBraces(pathname):
    '''
    glob.glob() after escaping "[" and "]".
    '''
    return glob.glob(escapeBraceForGlob(pathname))
  1. os.listdir() を使う。ただし、サブディレクトリのファイルまで列挙するので注意

参考

7
5
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
7
5