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?
__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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With