python glob issues with directory with [] in name

此生再无相见时 提交于 2019-12-10 23:28:43

问题


I am using glob to find all *.shp files within a directory, but the directory name contains '[]' and that is causing glob to fail. Any workarounds for this?

My code is:

glob.glob(sub_dir+os.sep+'soilmu_a_*.shp')

where sub_dir is:

'C:\\Users\\oh\\wss_SSA_OH001_soildb_OH_2003_[2013-12-19]\\spatial\\'

The error message I get is:

*** error: bad character range

回答1:


As suggested in the manual page, you can modify your pattern and wrap the offending meta characters. Change [ to [[] and ] to []] (single character ranges corresponding to the meta character).

For instance:

pattern = sub_dir + os.se p +'soilmu_a_*.shp'
pattern = pattern.replace('[','[[]').replace(']','[]]')
glob.glob(pattern)



回答2:


Yes, glob failed to find subdirectories when the parent directory path had [] in it, and I got NO error message! I found the problem by chance. I could wish that I had gotten an error message.

I switched to os.listdir to get the subdirectories, and since I needed the full path to the subdirectories, I had to paste that back in:

subdirs = [d for d in os.listdir(current_full_path) if os.path.isdir(current_full_path + '/' + d)]
for subdir in subdirs:
    subdir_full_path = current_full_path + '/' + subdir



回答3:


@isedev is right about the character range but double replacement is NOT a sensible thing to do.

import re
ptn = re.sub('([\[\]])','[\\1]',ptn)

str.translate() should also work



来源:https://stackoverflow.com/questions/22055500/python-glob-issues-with-directory-with-in-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!