Jump to content

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

From Wikipedia, the free encyclopedia
Computing desk
< July 15 << Jun | July | Aug >> July 17 >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


July 16

[edit]

does the file exist?

[edit]

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)[reply]

Use glob.glob -- Finlay McWalter··–·Talk 11:33, 16 July 2020 (UTC)[reply]
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.:
import glob

def exists(f):
    try:
        next(glob.iglob(f))
        return True
    except:    
        return False
-- Finlay McWalter··–·Talk 16:00, 16 July 2020 (UTC)[reply]
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 try doing so and catch the resulting exception if there are no matches. (FileNotFoundException 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)[reply]

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)[reply]

Right, you can use the x mode with open, and it will fail (throwing an exception) if the file already exists. --47.146.63.87 (talk) 01:42, 17 July 2020 (UTC)[reply]
Oops, never mind. Read that wrong the first time. --47.146.63.87 (talk) 06:13, 17 July 2020 (UTC)[reply]

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)[reply]