Check a file's existance without handling exceptions in Python

 

In order to check a file's existance without opening it and handling exception, python provides us os.path.isfile('path/to/file') in the standard os.path module.
>>> os.path.isfile('/home/pete/file01.py')
>>> True 
It returns True if the file exists, otherwise returns False.
You check a directory's existance using os.path.isdir('path/to/directory')
>>> os.path.isfile('/home/pete/pictures')
>>> True 
It returns True if the directory exists, otherwise returns False.
And also you can check a file or a directory's existance, using os.path.exists('/path/to/file/or/directory')
>>> os.path.exists('/home/pete/pictures')
>>> True

Starting with Python 3.4, it provides a object-oriented approach to acheive this end.
>>> from pathlib import Path
>>> file_path = Path('/home/pete/file01.py')
>>> file_path.is_file()
True
>>> file_path.is_dir()
False
>>> file_path.exists()
True


Comments

Popular posts from this blog

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

How to create a memory puzzle game with Python and Pygame (#005)

Introduction to multitasking with Python #001 multithreading (2020 tutorial)