Pathlib 和 stem - Attributerror

Pathlib and stem - Attributerror

作为代码的一部分,我的功能如下:

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}')

但是,我遇到了属性错误,无法解决,希望有任何建议?

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'

我是 Pathlib 和 stem 的新手,比我聪明的人建议我研究它,如果问题听起来像新手,我深表歉意

path.with_stem() 是在 Python 3.9 中引入的。在以前的版本(支持路径对象)中,您可以手动完成:

path = orig_path.with_name(f'{orig_path.stem}_{stem}{orig_path.suffix}')