【问题标题】:Pathlib and stem - AttributerrorPathlib 和 stem - Attributerror
【发布时间】:2021-05-19 08:58:08
【问题描述】:

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

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 非常陌生,比我聪明的人建议我研究一下,如果这个问题听起来很新手,请道歉

【问题讨论】:

  • 你的 Python 版本是多少? with_stem 最近才在 Python 3.9 中引入
  • 是的,你是对的,版本问题。我的是 3.8... 你有旧版本的解决方案/替代品吗?
  • 当然,我将其添加为答案
  • 感谢您的帮助

标签: python-3.x pathlib


【解决方案1】:

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

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

【讨论】:

  • 感谢您列出 3.9 之前的“旧”方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多