{"id":220,"hash":"b61215d028bcad9fa6db79e31ddcc927759f114b02dc37865f8682591b05fe66","pattern":"How do I check whether a file exists without exceptions?","full_message":"How do I check whether a file exists or not, without using the try statement?","ecosystem":"pypi","package_name":"file","package_version":null,"solution":"If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.\n\nIf you're not planning to open the file immediately, you can use os.path.isfile if you need to be sure it's a file.\n\nReturn True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.\n\nimport os.path\nos.path.isfile(fname)\n\npathlib\nStarting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):\n\nfrom pathlib import Path\n\nmy_file = Path(\"/path/to/file\")\nif my_file.is_file():\n    # file exists\n\nTo check a directory, do:\n\nif my_file.is_dir():\n    # directory exists\n\nTo check whether a Path object exists independently of whether is it a file or directory, use exists():\n\nif my_file.exists():\n    # path exists\n\nYou can also use resolve(strict=True) in a try block:\n\ntry:\n    my_abs_path = my_file.resolve(strict=True)\nexcept FileNotFoundError:\n    # doesn't exist\nelse:\n    # exists","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions","votes":7347,"created_at":"2026-04-19T04:41:34.548902+00:00","updated_at":"2026-04-19T04:51:46.371384+00:00"}