ZhuLinsen/daily_stock_analysis · error · FileNotFoundError

Context file not found: {path}

Error message

Context file not found: {path}

What it means

FileNotFoundError raised by _read_context_files in the screening context pipeline: every path passed in the context-files list must exist as a regular file, otherwise the screening run aborts. Files are read as UTF-8 text and injected as LLM context, so a missing file is treated as a configuration error rather than being silently skipped.

Source

Thrown at src/services/screening/context.py:329

        for source, weight in source_weights.items():
            text = _safe_context_value(source, max_len=40)
            if not text:
                continue
            try:
                items.append(f"{text}={float(weight):.2f}")
            except (TypeError, ValueError):
                continue
        if items:
            lines.append("来源权重: " + ",".join(items))
    return "\n".join(lines) if len(lines) > 1 else ""


def _read_context_files(paths: list[str | Path]) -> str:
    chunks: list[str] = []
    for path_like in paths:
        path = Path(path_like)
        if not path.is_file():
            raise FileNotFoundError(f"Context file not found: {path}")
        text = path.read_text(encoding="utf-8").strip()
        if text:
            chunks.append(f"# {path.name}\n{text}")
    return "\n\n".join(chunks)


def _read_candidate_context_files(
    paths: list[str | Path],
    candidate_df: pd.DataFrame | None,
) -> str:
    if not paths or candidate_df is None or candidate_df.empty or "code" not in candidate_df.columns:
        return ""

    candidate_names, candidate_order = _candidate_maps(candidate_df)
    candidate_codes = set(candidate_names)
    chunks: list[tuple[int, int, str]] = []
    row_position = 0
    for path_like in paths:

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Check the path exists from the process's actual cwd (os.getcwd()) — resolve relative paths against an explicit base dir before passing them in.
  2. Fix typos/renames, or re-create the missing file.
  3. If globs are needed, expand them yourself (glob.glob(...)) and pass concrete file paths, filtering out non-files.
  4. If missing context files should be tolerated, pre-filter with Path(p).is_file() before calling, and log a warning for skipped entries.

Example fix

# before
read_context_files(['notes/thesis.md'])  # FileNotFoundError if cwd differs

# after: resolve against a known base and filter
base = Path(__file__).parent
files = [p for p in [base / 'notes/thesis.md'] if p.is_file()]
text = _read_context_files(files)
Defensive patterns

Strategy: validation

Validate before calling

from pathlib import Path
paths = [Path(p).resolve() for p in context_files]
missing = [p for p in paths if not p.is_file()]
if missing:
    raise FileNotFoundError(f'context files missing: {missing}')
text = _read_context_files(paths)

Try / catch

try:
    text = _read_context_files(context_files)
except FileNotFoundError as e:
    log.warning('skipping missing context file: %s', e)
    text = ''  # only if context is optional for your run

Prevention

When it happens

Trigger: Running a screening task with context_files=['notes/thesis.md'] where the path is relative to a different working directory, has a typo, or the file was deleted/renamed after config was written. path.is_file() is false for directories too, so pointing at a folder raises the same error.

Common situations: Relative paths resolved against a cron/CI working directory instead of the project root; files synced incompletely to a server; absolute paths from another machine left in shared config; passing a directory or glob pattern instead of a file path.

Related errors


AI-assisted analysis of ZhuLinsen/daily_stock_analysis@5159bd72e8 (2026-08-15). Data as JSON: /api/errors/2af7cd8be5ee9393. Report an issue: GitHub.