I'm trying to use glob and os to locate the most recent .zip file in a directory. Funny thing is, I had the following set up and it was working previously:
max(glob.glob('../directory/*.zip'), key=os.path.getctime)
Running this now gets me max() arg is an empty sequence, which makes sense because when I try this:
glob.glob('../directory/*.zip')
it returns nothing but an empty list. Using the full path also gets me an empty list. Trying other directories also gets me an empty list. I'm very confused about what's going on here given this worked perfectly previously. Help?
EDIT: Got it to work again using:
glob.glob(/Users/*/directory/*.zip)
glob() method returns a list of files or folders that matches the path specified in the pathname argument.
glob (short for global) is used to return all file paths that match a specific pattern. We can use glob to search for a specific file pattern, or perhaps more usefully, search for files where the filename matches a certain pattern by using wildcard characters.
listdir is quickest of three. And glog. glob is still quicker than os.
The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported.
You want the **
glob operator:
glob.glob('**/*.zip',recursive=True)
Will match all files ending in '.zip' in the current directory and in all subdirectories for example.
In my case, I forgot to escape the special character [
that was in the directory name using glob.escape(pathname)
.
So instead of glob.glob(pathname)
, try glob.glob(glob.escape(pathname))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With