pythondirectorypathlib

Python Pathlib IndexError


I'm having trouble with using following lines on my AWS instance. Code works perfectly fine on my Macbook. What's the problem here? I've checked directory, it exists, there is not problem with path.

Image - code output

s = str(Path(Path('__file__').parents[1] / 'lib'))
print(s)

.

File "/usr/lib/python3.6/pathlib.py", line 594, in __getitem__
raise IndexError(idx)
IndexError: 1

Solution

  • As far as I understood you are trying to print the directory named lib which is a sibling to the parent[1] directory.

    But your Path('__file__') does not return the current file path.

    If you are looking to do this cd ../lib from your file directory, you should get the absolute path of the file first and go from there like below.

    samp.py

    from pathlib import Path
    import os
    print(os.path.abspath(__file__))
    s = str(Path(Path(os.path.abspath(__file__)).parents[1] / 'lib'))
    print(s)
    

    Output:

    ..../Downloads/f1/samp.py
    ..../Downloads/lib