Wikipedia:Reference desk/Archives/Computing/2020 July 16

= July 16 =

does the file exist?
In Python, how can I ask whether a file exists that matches a partial name (e.g. archive*.zip)? —Tamfang (talk) 00:13, 16 July 2020 (UTC)


 * Use glob.glob -- Finlay McWalter··–·Talk 11:33, 16 July 2020 (UTC)


 * Strictly, glob.glob is eager, which might be an issue if you have a potentially very large number of matches, and/or a slow folder (e.g. on a network share) - because it will read all the directory entries, even if you only care about whether there is a single match. The solution, iff you actually have this case, is to use glob.iglob, which is a generator, and thus is lazy. e.g.:


 * -- Finlay McWalter··–·Talk 16:00, 16 July 2020 (UTC)
 * However, I'll add that checking for existence directly is only needed if you want to do something such as spit out information to the user, like "directory foo contains 0 files matching archive*.zip". If you want to operate on the files, just  doing so and catch the resulting exception if there are no matches. (  I think? Not a Python guru.) This is one of the things that's handy about exceptions. No checking for fifteen different things like in C and I hope you didn't forget any, like checking whether a pointer is null! Oops, you just introduced a security hole that someone will come along and exploit later! --47.146.63.87 (talk) 18:45, 16 July 2020 (UTC)

Thanks y'all! Here's my story. I generate lots of algorithmic image files, and my convention is to name them [parameters]-[creator].png, thus a file made by foo.py will have a name ending in *-foo.png. I want to skip generating the file if it has already been made by any program, not only the same program, hence a check for [parameters]-*.png. (One of the "parameters" is usually generated by the program itself.) —Tamfang (talk) 00:48, 17 July 2020 (UTC)
 * Right, you can use the  mode with, and it will fail (throwing an exception) if the file already exists. --47.146.63.87 (talk) 01:42, 17 July 2020 (UTC)
 * Oops, never mind. Read that wrong the first time. --47.146.63.87 (talk) 06:13, 17 July 2020 (UTC)

any(glob.iglob(f)) should get rid of the need for dealing with the exception. 2601:648:8202:96B0:0:0:0:5B74 (talk) 20:21, 23 July 2020 (UTC)