Python Check If File or Directory Exists

Created with Sketch.

In Python, you can use the os module to check if a file or directory exists. Here’s a simple example:

import os

def check_file_exists(file_path):
    return os.path.exists(file_path)

# Example usage:
file_path = 'path/to/your/file.txt'

if check_file_exists(file_path):
    print(f"The file or directory at '{file_path}' exists.")
else:
    print(f"The file or directory at '{file_path}' does not exist.")

In Python, you can use the os module to check if a file or directory exists. Here’s a simple example:

python
import os def check_file_exists(file_path): return os.path.exists(file_path) # Example usage: file_path = 'path/to/your/file.txt' if check_file_exists(file_path): print(f"The file or directory at '{file_path}' exists.") else: print(f"The file or directory at '{file_path}' does not exist.")

In this example:

  • Replace 'path/to/your/file.txt' with the actual path you want to check.

The os.path.exists() function returns True if the specified path (file or directory) exists and False otherwise.

If you specifically want to check if it’s a file or a directory, you can use os.path.isfile() and os.path.isdir() functions:

import os

def check_file_or_directory(file_path):
    if os.path.exists(file_path):
        if os.path.isfile(file_path):
            print(f"'{file_path}' is a file.")
        elif os.path.isdir(file_path):
            print(f"'{file_path}' is a directory.")
    else:
        print(f"The file or directory at '{file_path}' does not exist.")

# Example usage:
path_to_check = 'path/to/your/file_or_directory'

check_file_or_directory(path_to_check)

This will print whether the specified path is a file, a directory, or if it doesn’t exist.

 

Leave a Reply

Your email address will not be published. Required fields are marked *