Pathlib and stem – Attributerror

Question:

as part of a code I have function as follow:

def match_output(orig_path: Path,lines: Iterable[str],stem: str, delim: str,delim_pred: Callable[[int], bool],) -> Iterable:
    n = 0
    path = orig_path.with_stem(f'{orig_path.stem}_{stem}')

    with path.open('w') as f:
        for line in lines:
            n_delim = line.count(delim)
            matched = delim_pred(n_delim)
            if matched:
                f.write(line)

            n += int(matched)
            yield

    logger.info(f'Number of {stem} lines: {n}')

However, I am getting attribute error, couldn’t solve it, would appreciate any suggestion?

Traceback (most recent call last):
  File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 95, in <module>
    main()
  File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 88, in main
    process(
  File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 82, in process
    for n_lines, _ in enumerate(zip(*iters)):
  File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 27, in match_output
    path = orig_path.with_stem(f'{orig_path.stem}_{stem}')
AttributeError: 'WindowsPath' object has no attribute 'with_stem'

I am very new to Pathlib and stem, someone smarter than me recommended that I look into it so apologize if the question sounds newbie

Asked By: Sam.H

||

Answers:

path.with_stem() was introduced in Python 3.9. In previous versions (that support path objects) you can do it manually:

path = orig_path.with_name(f'{orig_path.stem}_{stem}{orig_path.suffix}')
Answered By: Jan Wilamowski
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.