🔍 Code Extractor

function check_file_exists

Maturity: 39

Checks if a file exists at the specified filepath and prints a formatted status message with a description.

File:
/tf/active/vicechatdev/email-forwarder/setup_venv.py
Lines:
27 - 34
Complexity:
simple

Purpose

This utility function verifies file existence using pathlib.Path and provides user-friendly console feedback with checkmark/cross emojis. It's commonly used in setup scripts, validation routines, or pre-flight checks to ensure required files are present before proceeding with operations.

Source Code

def check_file_exists(filepath, description):
    """Check if a file exists."""
    if Path(filepath).exists():
        print(f"✅ {description} - Found")
        return True
    else:
        print(f"❌ {description} - Not found")
        return False

Parameters

Name Type Default Kind
filepath - - positional_or_keyword
description - - positional_or_keyword

Parameter Details

filepath: String or Path-like object representing the path to the file to check. Can be absolute or relative path. Accepts any path format that pathlib.Path can handle (e.g., '/home/user/file.txt', 'data/config.json', Path object).

description: String describing the file being checked, used in the console output message. Should be a human-readable label (e.g., 'Configuration file', 'Input dataset', 'Model weights').

Return Value

Returns a boolean value: True if the file exists at the specified filepath, False if it does not exist. This allows the function to be used in conditional statements for flow control.

Dependencies

  • pathlib

Required Imports

from pathlib import Path

Usage Example

from pathlib import Path

def check_file_exists(filepath, description):
    """Check if a file exists."""
    if Path(filepath).exists():
        print(f"✅ {description} - Found")
        return True
    else:
        print(f"❌ {description} - Not found")
        return False

# Example usage
config_exists = check_file_exists('config.json', 'Configuration file')
if config_exists:
    print('Proceeding with configuration...')
else:
    print('Please create config.json first')

# Check multiple files
files_to_check = [
    ('data/input.csv', 'Input data'),
    ('models/weights.h5', 'Model weights'),
    ('.env', 'Environment variables')
]

all_present = all(check_file_exists(path, desc) for path, desc in files_to_check)

Best Practices

  • Use this function for validation checks before file operations to provide clear user feedback
  • The function checks existence only, not whether the path is a file vs directory - use Path.is_file() if you need to distinguish
  • Consider wrapping in try-except if checking paths with permission issues or invalid characters
  • The description parameter should be concise and descriptive for clear console output
  • This function has side effects (prints to console) - consider separating validation logic from output if you need silent checks
  • For checking multiple files, consider collecting results before printing to provide a summary
  • The function works with both files and directories since Path.exists() returns True for both - use Path.is_file() if you specifically need to verify it's a file

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function ensure_dir_exists 56.9% similar

    Creates a directory and all necessary parent directories if they don't already exist, with logging support.

    From: /tf/active/vicechatdev/msg_to_eml.py
  • function check_filecloud_structure 56.9% similar

    Diagnostic function that checks the FileCloud server structure and verifies accessibility of various paths including root, SHARED, and configured base paths.

    From: /tf/active/vicechatdev/SPFCsync/check_filecloud_structure.py
  • function ensure_path_exists 54.5% similar

    Recursively creates a directory path in FileCloud storage by ensuring all parent directories exist before creating child directories.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function ensure_dir 52.1% similar

    Creates a directory and all necessary parent directories if they don't already exist, returning a boolean indicating success or failure.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function check_static_files 49.6% similar

    Scans a 'static' directory for CSS and JavaScript files and prints their modification times relative to the current time.

    From: /tf/active/vicechatdev/vice_ai/dev_tools.py
← Back to Browse