gpt4 book ai didi

python - Pathlib 使用 Path.parents 访问 Path 时出错

转载 作者:行者123 更新时间:2023-12-01 02:11:14 25 4
gpt4 key购买 nike

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

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

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

最佳答案

__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)

(在打开的文件对象上调用 list 会给出所有行)。

演示:

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

关于python - Pathlib 使用 Path.parents 访问 Path 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com