[Tutor] (no subject)
Steven D'Aprano
steve at pearwood.info
Mon Aug 20 00:19:04 CEST 2012
On Sun, Aug 19, 2012 at 08:29:22PM +0100, Selby Rowley Cannon wrote:
> OK, I have some code, and it uses glob.glob('*.py') to find all the
> python files in the current directory.
That works because if you don't specify an absolute directory, the
current directory is used. It does not look inside subdirectories.
> Just thought i'd ask, would:
>
> glob.glob('C:\*.py') (Windows), or
By the way, that only works by accident. Backslashes are special in
Python, and should be escaped like this:
'C:\\*.py'
or by using a raw string which turns off backslash interpretation:
r'C:\*.py'
or most easy of all, take advantage of Windows' feature that it allows
you to use either backslashes or forward slashes:
'C:/*.py'
In your specific case, it works by accident because \* is interpreted as
a literal backslash followed by an asterisk, but if you wrote something
like 'C:\n*' hoping to find files that start with the letter "n", you
would actually be looking for C : NEWLINE star instead.
> glob.glob('/*.py') (*nix)
>
> find all the python files on the system? Thanks
No, because that specifies an absolute directory, but does not look
inside subdirectories.
You can tell glob to look one, two, three... levels deep:
glob.glob('/*.py')
glob.glob('/*/*.py')
glob.glob('/*/*/*.py')
but there's no way to tell it to look all the way down, as far as it
takes. For that sort of "recursive glob", you can use a combination of
os.walk and the fnmatch module to do the same thing. Or look at the
various solutions listed here:
http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
--
Steven
More information about the Tutor
mailing list