Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python glob.glob always returns empty list

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)

like image 945
TheVideotapes Avatar asked Jun 03 '16 16:06

TheVideotapes


People also ask

Does glob return a list?

glob() method returns a list of files or folders that matches the path specified in the pathname argument.

What does glob glob do in Python?

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.

Is glob faster than OS Listdir?

listdir is quickest of three. And glog. glob is still quicker than os.

Does glob use regex?

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.


2 Answers

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.

like image 183
jb4earth Avatar answered Oct 12 '22 21:10

jb4earth


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)).

like image 37
Jordan Draper Avatar answered Oct 12 '22 23:10

Jordan Draper