AttributeError: ‘Str’ Object Has No Attribute ‘Glob’ | Fast Fix

A plain string where Python expects a Path object triggers the ‘Str’ object has no attribute ‘glob’ error when code calls glob().

What This AttributeError Glob Message Actually Means

Quick overview — This error comes from Python when code tries to call .glob() on a plain string instead of on an object that actually provides that method, such as a pathlib.Path instance.

How Python Reads It — Under the hood, the interpreter looks at the value on the left side of the dot. If that value is a string, its type is str, and the standard string type does not define a glob attribute or method, so the runtime raises an AttributeError.

Name lookup rules — When you write obj.glob(), Python first checks the type of obj and then searches that type’s attribute dictionary for the exact name 'glob'. The lookup is case sensitive. If you mis-type the method name or attach it to a type that was never designed for pattern matching, the attribute search fails and the interpreter falls back to raising an AttributeError.

Strings versus path objects — Strings only know about characters, slices, and basic text methods. Path objects bundle file system behaviour such as joining segments, resolving symlinks, and running glob searches. When code treats a path as an object in one place and as a bare string somewhere else, attribute errors like this one surface for most projects.

Why Glob Shows Up Here — The glob name usually appears when you work with file patterns such as "*.csv" or "*.txt". Many developers mix two styles in the same project: the older glob module and the newer pathlib.Path.glob() method. When that mix is not handled carefully, this specific error pops up.

Why You See AttributeError: ‘Str’ Object Has No Attribute ‘Glob’ In Python

First trigger — A function that expects a Path object may receive a raw string. Later in that function the code calls path.glob("*.json"). When the value is actually a string, the runtime tries to use the string type and fails with this exact message.

Second trigger — A helper may join paths using os.path.join and then pass the result into logic that assumes a Path instance. Again, that helper ends up holding a string, so calling .glob() on it fails.

Third trigger — Some projects shadow variable names. A developer might import pathlib.Path as Path and later store a plain string in a variable that once held a Path. The name stays the same, but the value changes, so the method call no longer matches the object type.

  • Glob call near a join — The failing line often sits near a call to os.path.join, which leaves you with a plain string instead of a Path object.
  • Traceback from helper code — The stack trace may point into a shared helper where colleagues pass a mix of types, so the bug shows up only under certain call paths.
  • Works on some machines — On one system a caller hands over a Path, on another it passes a string, so the error appears only for part of the team.

Fixing ‘Str’ Object Has No Attribute ‘Glob’ Errors In Real Code

Main idea — The fix is always the same: pass and store real path objects wherever the code later calls .glob(). Instead of treating paths as untyped strings, convert them once at the edge of your program and keep that type stable.

  1. Check the failing line — Inspect the traceback and find the exact line where .glob() runs. Confirm which variable sits on the left side of the dot.
  2. Inspect the variable type — Drop a temporary print(type(path_var)) or use a debugger to confirm whether that value is a string or a Path instance.
  3. Trace where the value comes from — Walk back through the function calls or assignments that build that variable. Identify the first place where it turns into a string.
  4. Convert early to Path — Wrap user input or configuration values with Path(...) as soon as they enter your code so later calls to .glob() see a consistent type.
  5. Avoid mixing styles — Stick with either pathlib.Path or the older glob module inside any given code path so you do not bounce between strings and path objects.

Small refactor — Often the real cure is to choose one place where you create a Path instance and pass that object through your functions instead of rejoining or recomputing paths as plain strings every time.

Shared helper pattern — A tidy way to keep this under control is to build a small function that accepts anything path-like and always returns a Path object. Every call site then goes through that helper, which keeps the conversion logic in one place instead of scattered across the code base.

Step-By-Step Fix For ‘Str’ Object Has No Attribute ‘Glob’

Sample failing snippet — This compact script shows a pattern that commonly raises the classic ‘Str’ object has no attribute ‘glob’ message:

from pathlib import Path

data_dir = "/tmp/data"

for file_path in data_dir.glob("*.csv"):
    print(file_path)

Core problem — Here data_dir is a string, so Python reads data_dir.glob as a request to call a method on the string object. Since the string type does not expose glob, the runtime raises the AttributeError: ‘Str’ Object Has No Attribute ‘Glob’ message.

Direct fix — Change the value into a Path instance before you call .glob():

from pathlib import Path

data_dir = Path("/tmp/data")

for file_path in data_dir.glob("*.csv"):
    print(file_path)

Alternative pattern — Some developers prefer to call glob on the module and keep paths as strings. That style also works, as long as you keep the pattern consistent:

import glob
import os

data_dir = "/tmp/data"
pattern = os.path.join(data_dir, "*.csv")

for file_path in glob.glob(pattern):
    print(file_path)

Takeaway — Pick one style and keep it steady. Either treat paths as objects and call .glob() on the path instance, or treat paths as strings and call glob.glob() with an explicit pattern.

Safer Patterns For File Path Handling With Glob

Group related logic — When you gather file paths in many parts of a project, a tiny helper function can reduce type confusion.

from pathlib import Path

def iter_csv_files(root):
    root = Path(root)
    yield from root.glob("*.csv")

Benefits — The helper normalises root up front so callers can pass either strings or Path instances. The rest of your code only deals with path objects, which removes the risk of calling .glob() on a string.

  • Accept flexible inputs — Take both strings and Path objects at module boundaries, then convert to Path inside the function.
  • Return clear outputs — Decide whether functions return path objects, strings, or opened file handles so the next layer always knows what to expect.
  • Keep names honest — Use variable names like root_path or base_dir only for values that already hold Path instances.
Symptom Likely Cause Quick Fix
AttributeError raised on .glob() Variable holding the directory is a plain string Wrap the value with Path(...) before calling .glob()
Error only on some platforms Different code paths send different path types into the same helper Normalise all inputs through a single helper that returns a Path
Glob returns no matches without errors Pattern built with a mix of separators or an incorrect working directory Print the final pattern or Path and confirm it matches what the file system shows

Platform quirks — Paths differ between operating systems, so slashes and drive letters may vary. By leaning on pathlib.Path and its glob() method instead of manual string building, your code keeps those quirks inside the standard library instead of scattering conditionals through your own functions.

Mixed library scenarios — Larger projects sometimes blend libraries that expect strings with libraries that prefer Path objects. In that setting, it helps to draw a boundary layer where you consciously convert between the two, instead of doing ad hoc conversions deep inside business logic.

Worked Examples Of Correct Glob Code

CSV report loader — This example shows a short script that loads all CSV files from a directory and passes them into a processing function without ever storing paths as raw strings:

from pathlib import Path

def load_reports(report_dir):
    report_path = Path(report_dir)
    for csv_file in report_path.glob("*.csv"):
        yield csv_file.read_text()

for content in load_reports("/tmp/reports"):
    print(content[:80])

Log rotation script — Here a small function removes old log files that match a pattern, using Path.glob() in a single place:

from pathlib import Path
from datetime import datetime, timedelta

def purge_old_logs(root, days):
    root_path = Path(root)
    cutoff = datetime.now() - timedelta(days=days)
    for log_file in root_path.glob("*.log"):
        if log_file.stat().st_mtime < cutoff.timestamp():
            log_file.unlink()

Recursive image finder — In photo or asset tools you may want to walk through nested folders. The rglob method lets a Path object search through subdirectories while still keeping the type safe:

from pathlib import Path

def find_png_files(root):
    root_path = Path(root)
    return list(root_path.rglob("*.png"))

Why this helps — By collecting the logic into a dedicated function you remove the temptation to sprinkle path handling code across many modules. Callers pass in either a string or a Path, the helper converts once, and every later operation relies on methods that belong to the correct type.

Unit test fixture — In tests, you can rely on tmp_path from pytest or similar helpers, which already provide Path objects. When you call tmp_path.glob(), you avoid the original error message altogether because the fixture guarantees the right type.

Checklist To Prevent This AttributeError Next Time

Before you run — A short checklist can stop this error from returning once you have patched the failing line.

Simple mental model — Ask a quick question before each .glob() call: “Is this value a path object or just text?” When that question has a clear answer across the file, surprises fade and you catch type slips while reading the code during everyday debugging tasks.

  • Standardise your path style — Pick either pathlib.Path everywhere or a consistent combination of strings and the glob module.
  • Create paths at the edge — Convert user input, configuration values, and env variables into Path objects as they enter the program.
  • Type hint your helpers — Add static type hints such as path: Path to function signatures so mismatches surface during code review or tooling runs.
  • Watch your imports — Avoid shadowing names like Path or glob with local variables, which may hide the real objects you intend to use.
  • Add regression tests — Write a tiny test that calls the globbing helper with both a string and a Path object so the test suite catches regressions.

Habit to build — Treat file-system paths as structured data, not as loose strings. When you do that, method calls such as .glob() stay attached to the right objects, and AttributeError: ‘Str’ Object Has No Attribute ‘Glob’ stops appearing in your tracebacks.