Quantcast
Viewing all articles
Browse latest Browse all 46

Answer by Memin for How do I check whether a file exists without exceptions?

TL;DR
answer is: 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.

from pathlib import Pathif Path("myfile.txt").exists(): # works for both file and folders    # do your cool stuff...

The pathlib module was introduced in Python 3.4, so you need to have Python 3.4+, this lib makes your life much easier while working with files and folders and it is pretty to use, here is more doc about it (https://docs.python.org/3/library/pathlib.html).

BTW, if you are going to reuse the path, then it is better to assign it to a variable

so will become

from pathlib import Pathp = Path("loc/of/myfile.txt")if p.exists(): # works for both file and folders    # do stuffs...#reuse 'p' if needed.

Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>