Sometimes you need to check if a file exists on your file system. Here are different ways to accomplish this.
The most Pythonic way to do this is to simply try accessing the file, while catching any exceptions that occur in case the file doesn't actually exist. For example:
try: my_file = open(filename) except IOError: # file didn't exist (or other issues) pass
You can wrap this in a function, although that somewhat defeats the purpose of using this approach:
def file_exists(filename): try: my_file = open(filename) my_file.close() return True except IOError: # file didn't exist (or other issues) return False
os module has a
path component with an
>>> import os >>> os.path.exists("test.txt") True >>> os.path.exists("fake.txt") False
Note, however, that this returns
True for files and directories, so you
can instead use
isfile if only files should be accepted:
>>> os.path.isfile("test.txt") True
Python 3 includes a module named
pathlib that lets you define a
Path has an
exists method you can use:
>>> import pathlib >>> path = pathlib.Path("test.txt") >>> path.exists() True >>> path.is_file() True
Even though you check that a file exists, there is no guarantee that the file
won't be removed immediately after your check was performed. That's why
opening the file inside a
catch block is preferred; that way, even if
the file is removed, you still have a handle to it.
Try our practical beginner lessons, or test your skills with our challenges.