Search code examples
pythonstringwhile-looppython-os

How to check if a file exists in a folder starting with a substring and ending with a substring in Python


I wanna wait for a file to donwload, and I want to check on a folder while the file not exists I'll put a time untill the file finish the download. The problem is I wanna check if the file exists starting with a substring variable called 'final_name' and ends with '.csv'. Could someone help me?

    final_name = name.replace(" ", "").replace('(', '').replace(')', '').replace('-', '')\
        .replace('/', '').replace(r"'", '')

    print(final_name)

    time.sleep(5)

    while not os.path.exists(final_name):
        time.sleep(1)

Solution

  • You can use this function to check if the file exists. It lists all files in a directory and loops over them and checks if a file starts and ends with the specified strings.

    Code:

    import os
    
    def path_exists(directory, start, end):
        files = os.listdir(directory)
        for file in files:
            if file.startswith(start) and file.endswith(end):
                return True
        return False
    
    # "./" is the current directory.
    print(path_exists("./", final_name, ".csv"))