Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Thursday, January 9, 2020

Check file, directory or path exists in python

            The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system.

codesimple.info

1. path.exists()

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.


This will check if something exists in the given name/path and not specifically check if a file exists on that name/path.


2. Check if it is file

This function will specifically check if there is a file in the given name or path.



3. To check if a directory exists

The isdir() function lets you check whether a directory of a given name exists or not.



4. check using Try block

You can also use resolve(strict=True) in a try block:

If the path doesn’t exist and strict is True, FileNotFoundError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists. If an infinite loop is encountered along the resolution path, RuntimeError is raised.





#python #files #file_exists

No comments:

Post a Comment