3

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

3
  • 2
    what is your Python version? with_stem was only recently introduced in Python 3.9 May 19, 2021 at 9:00
  • Yes you're right, version issue. Mine is 3.8... Do you have any solution/replacement for older version?
    – Sam.H
    May 19, 2021 at 11:26
  • sure, I added it as an answer May 20, 2021 at 1:33

1 Answer 1

10

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}')
1
  • Thanks for listing the 'old' way of doing it before 3.9
    – Hugh Ward
    Nov 26, 2021 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.