【问题标题】:Pathlib Error accessing Path with Path.parentsPathlib 使用 Path.parents 访问路径时出错
【发布时间】:2018-07-19 02:37:12
【问题描述】:

为什么当我在 Python IDE (PyCharm) 中运行以下 sn-p 代码时:

import os
from pathlib import Path

if os.path.isfile('shouldfail.txt'):
    p = Path(__file__).parents[0]
    p2 = Path(__file__).parents[2]
    path_1 = str(p)
    path_2 = str(p2)

    List = open(path_1 + r"/shouldfail.txt").readlines()
    List2 = open(path_2 + r"/postassembly/target/generatedShouldfail.txt").readlines()

它工作正常并返回所需的结果,但是当我通过命令行运行脚本时,我收到错误:

File "Script.py", line 6, in <module>
    p2 = Path(__file__).parents[2]
  File "C:\Users\Bob\AppData\Local\Programs\Python\Python36\lib\pathlib.py", line 594, in __getitem__
    raise IndexError(idx)
IndexError: 2

我在这里缺少什么? 还有一种更好/更简单的方法可以从我正在运行脚本的当前路径向上移动两个文件夹(在脚本内)?

【问题讨论】:

    标签: python python-3.x pycharm index-error pathlib


    【解决方案1】:

    __file__ 可以是相对路径,它是只是 Script.py(如您的回溯中所示)。

    先解析成绝对路径:

    here = Path(__file__).resolve()
    p = here.parents[0]
    p2 = here.parents[2]
    

    注意open() 接受pathlib.Path() 对象,无需将它们转换为字符串。

    换句话说,以下工作:

    with open(path_1 / "shouldfail.txt") as fail:
        list1 = list(fail)
    
    with open(path_2 / "postassembly/target/generatedShouldfail.txt") as generated:
        list = list(generated)
    

    (打开文件对象的调用列表为您提供所有行)。

    演示:

    >>> from pathlib import Path
    >>> Path('Script')
    WindowsPath('Script')
    >>> Path('Script').resolve()
    WindowsPath('C:\\Users\\Bob\\Further\\Path')
    >>> Path('Script').resolve().parents[2] / 'shouldfail.txt'
    WindowsPath('C:\\Users\\Bob\\shouldfail.txt')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 2019-10-12
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多