check file Existing with Python Script

Discussion in 'Python' started by Gabriel9999, Apr 23, 2020.

  1. Gabriel9999

    Gabriel9999 New Member

    Joined:
    Mar 12, 2019
    Messages:
    23
    Likes Received:
    1
    Trophy Points:
    3
    Are there any way to check the file existence in Python script.
     
  2. marblete

    marblete New Member

    Joined:
    May 17, 2021
    Messages:
    3
    Likes Received:
    3
    Trophy Points:
    3
    Gender:
    Male
    Yes there is, you just need the pathlib library

    if you want to search inside all the sub directories of a directory for your file, you can use this recursive function (DFS)
    Code:
    from pathlib import Path
    
    def file_exists(origin,filename):
     
        for i in [x for x in Path(origin).iterdir()]:
         
            if i.name == filename:
                return True
            elif i.is_dir():
                t = file_exists(i,filename)
                return t
        return False
    
    Usage:
    Code:
    print(file_exists(/home/user/Documents/,'myhomework.pdf')
    
    But if you want to check the existance of a file in the running directory you can use this:
    Code:
    from pathlib import Path
    myfile = 'main.py'
    print(Path(myfile).exists())
    
    Hope it helps
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice