TL;DR
answerThe answer is: use the pathlib
module
Pathlib is probably the most modern and convenient way for almost all of the file operations. For the existence of a file or a folder a single line of code is enough. If file is not exists, it will NOTnot throw any exception.
from pathlib import Path
if Path("myfile.txt").exists(): # works for both file and folders
# do your cool stuff...
The pathlib
module was introduced in Python 3.4
Python 3.4, so you need to have Python 3.4+, this lib. This library makes your life much easier while working with files and folders, and it is pretty to use, here. Here is more docdocumentation about it: (https://docs.python.org/3/library/pathlib.html)pathlib — Object-oriented filesystem paths.
BTW, if you are going to reuse the path, then it is better to assign it to a variable.
soSo it will become:
from pathlib import Path
p = Path("loc/of/myfile.txt")
if p.exists(): # works for both file and folders
# do stuffs...
#reuse 'p' if needed.