[Tutor] Escaping globs for glob.iglob()

Peter Otten __peter__ at web.de
Tue Aug 21 08:05:03 CEST 2012


Ray Jones wrote:

> The code:
> 
>   curDir = os.getcwd()
>   znDir = shutil.abspath('../')
>   baseDir = shutil.abspath('../../')
> 
>   Files = glob.iglob(os.path.join(znDir, '*'))
>   print Files
>  
>   for moveFile in Files:
>     print moveFile
>     shutil.move(moveFile, curDir)
> 
> Nothing happens. The 'print...moveFile' never happens, even though print
> Files shows it to be an iglob generator object.
> 
> After reading over the glob docs and working the directories backward
> manually, I realized that one of the directory names in the znDir path
> begins with '[1st]'. According to the docs, glob is apparently seeing
> that as a character range. No problem, I'll simply escape the '[' and
> ']' with backslashes.  I used:
> 
> znDir = znDir.replace('[', '\[')
> and then
> znDir = znDir.replace(']', '\]')
> 
> No such luck. Glob still does not recognize the file glob in znDir/*.
> Later in the code I will be using creating symbolic links, and I wish to
> use the absolute path rather than the relative path.
> 
> Any idea of how to sanitize this path so that I can get glob to work?

Try

znDir = znDir.replace("[", "[[]")

Alternatively use os.listdir(znDir):

[os.path.join(znDir, name) for name in os.listdir(znDir)]

For a non-trivial file pattern:

pattern = "*tmp*.py"
files = [os.path.join(znDir, name) for name in 
 fnmatch.filter(os.listdir(znDir), pattern)]



More information about the Tutor mailing list