DEV Community

IntelliTools
IntelliTools

Posted on

How to Validate File Paths with Python CLI Without API Calls

When working with file systems in Python, one of the most common pain points is verifying whether a file exists at a specific path. This is especially true when dealing with batch processing or automation workflows where you need to ensure that input files are present before proceeding. The File Exists At Path Nyx_Data/Deliverable tool is designed to handle this exact scenario, but even if you're not using the tool, understanding how to validate file paths is a crucial skill for any Python developer.

In this article, we'll walk through how to write a simple command-line tool that checks if a file exists at a given path using Python's standard library. We'll also show how to extend this to support multiple input formats like .json and .csv, and how to handle malformed or empty input gracefully.


The Problem: Verifying File Existence in Python

In Python, you can check if a file exists using os.path.exists() or pathlib.Path.exists(). However, when working with automation or data processing, you often need to validate multiple files at once. This is where command-line tools shine, as they allow you to process files in bulk and output structured results.

Let's start by writing a basic script that checks if a file exists at a specified path.

import os
import argparse

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

def main():
    parser = argparse.ArgumentParser(description='Check if a file exists at a given path.')
    parser.add_argument('--input', required=True, help='Path to the input file (.json or .csv)')
    parser.add_argument('--output', help='Path to write results (.json)')
    parser.add_argument('--verbose', action='store_true', help='Print progress to stderr')

    args = parser.parse_args()

    if args.verbose:
        print("Checking file existence for:", args.input)

    result = {
        "file_path": args.input,
        "exists": check_file_exists(args.input),
        "error": None
    }

    if args.output:
        import json
        with open(args.output, 'w') as f:
            json.dump(result, f)
        if args.verbose:
            print(f"Results written to {args.output}")

    if args.verbose:
        print("File existence check complete.")

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

This script takes an input file path, checks if it exists, and writes the result to a JSON file if an output path is provided. It also supports a --verbose flag to show progress.


Extending the Tool to Handle Multiple Files

If you're processing multiple files, you can extend this script to read from a .json or .csv file and check each entry. Here's an example of how to do that:

import os
import argparse
import json
import csv
import sys

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

def process_file(path, verbose):
    exists = check_file_exists(path)
    if verbose:
        print(f"File {path} exists: {exists}")
    return {
        "file_path": path,
        "exists": exists,
        "error": None
    }

def main():
    parser = argparse.ArgumentParser(description='Check if files exist at given paths.')
    parser.add_argument('--input', required=True, help='Path to the input file (.json or .csv)')
    parser.add_argument('--output', help='Path to write results (.json)')
    parser.add_argument('--verbose', action='store_true', help='Print progress to stderr')

    args = parser.parse_args()

    if args.verbose:
        print("Starting file existence check...")

    results = []

    if args.input.endswith('.json'):
        with open(args.input, 'r') as f:
            data = json.load(f)
            for item in data:
                results.append(process_file(item['file_path'], args.verbose))
    elif args.input.endswith('.csv'):
        with open(args.input, 'r') as f:
            reader = csv.DictReader(f)
            for row in reader:
                results.append(process_file(row['file_path'], args.verbose))
    else:
        print("Unsupported input format. Use .json or .csv.")
        sys.exit(1)

    if args.output:
        import json
        with open(args.output, 'w') as f:
            json.dump(results, f)
        if args.verbose:
            print(f"Results written to {args.output}")

    if args.verbose:
        print("File existence check complete.")

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

This version reads from a .json or .csv file, processes each entry, and writes the results to a JSON file. It also handles malformed or empty input gracefully by skipping invalid entries.


Why You Should Care

Whether you're using the File Exists At Path Nyx_Data/Deliverable tool or writing your own, the ability to validate file paths is essential for reliable automation. This script demonstrates how to build a simple yet powerful CLI tool that can be extended to fit your specific needs. The tool is self-contained, requires no API keys, and works entirely in the local environment — making it ideal for DevOps pipelines, data processing workflows, and system automation.

If you're looking for a ready-to-run solution that does exactly this, you can find the File Exists At Path Nyx_Data/Deliverable tool at https://intellitools.gumroad.com/l/file-exists-at-path-nyx-data-deliverable. It includes all the features we've discussed and more, with a clear README and requirements file to get you up and running in minutes.

Top comments (0)