0

I'm aware that I can do either of the two to get the full path to a file:

>>> import os
>>> import pathlib
>>> path1 = str(pathlib.Path('filename').parent.absolute())
>>> path2 = os.path.abspath('filename')

The current structure of the absolute path to filename is /home/user/directory/filename. However, when I print the two variables path1 and path2 I only get /home/user/filename with the directory omitted.

Would anybody know why this happens, and how I can fix it? Thanks.

Sean
  • 2,890
  • 8
  • 36
  • 78
  • You are providing a string `filename`. You could call this string anything and it would still return a path even to a filename that doesn't exist. There is no connection between the string `filename` and the path `/home/user/directory/filename`. To get the path of the python file the script is running in you do `os.path.abspath(__file__)` – Tin Nguyen May 14 '20 at 11:10
  • Hmm is there no other way, or a way to use the `__file__` variable to get the specific path to another file? The reason why I'm doing `filename` as a string is because there's a specific file that I'm planning on using with `subprocess.call` to run in the script. – Sean May 14 '20 at 11:13
  • Use `os.path.join()` https://stackoverflow.com/questions/17429044/constructing-absolute-path-with-os-path-join – Tin Nguyen May 14 '20 at 11:21
  • why can't you just do `Path('/home/user/directory')` and then join whatever file name you need to that? – gold_cy May 14 '20 at 11:36
  • Well I'm trying to make my code a bit flexible for others to possibly use as they may have the specific file in other locations. I thought it'd be convenient for the script to automatically find the location with minimum intervention on the user's end. – Sean May 14 '20 at 12:00

0 Answers0