Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pathlib Error accessing Path with Path.parents

Why when I run the following snippet code in 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()

It works fine and returns the desired results, but when I run the script through the command line, I get the error:

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

What am I missing here? Also is there a better/easier way to move two folders up (inside the script) from the current path where I'm running the script?

like image 323
Xllion Avatar asked May 10 '26 23:05

Xllion


1 Answers

__file__ can be a relative path, it is just Script.py (as shown in your traceback).

Resolve it into an absolute path first:

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

Note that open() accepts pathlib.Path() objects, there is no need to convert these to strings.

In other words, the following works:

with open(path_1 / "shouldfail.txt") as fail:
    list1 = list(fail)

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

(calling list on an open file object gives you all the lines).

Demo:

>>> 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')
like image 65
Martijn Pieters Avatar answered May 13 '26 13:05

Martijn Pieters