Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pathlib.Path().resolve() and pathlib.Path().parent

I'm having a bit of a hard time understanding the difference between pathlib.Path().resolve() and pathlib.Path().parent.

If I want to be able to get the directory of the current script, do these serve the same purpose?

And are both of these location-agnostic, i.e. if I were to move the files to a different location, would my script still run?

like image 590
CharlieCCC Avatar asked Oct 30 '25 13:10

CharlieCCC


1 Answers

The method pathlib.Path().resolve() will return an absolute path. If the path is already absolute the method will have no effect.

For example assuming you are in the working directory /home/python and run the following

In: pathlib.Path().resolve()
Out: "/home/python"

In: pathlib.Path(".").resolve()
Out: "/home/python"

In: pathlib.Path("foo/bar.txt").resolve()
Out: "/home/python/foo/bar.txt"

In: pathlib.Path("/home/python").resolve()
Out: "/home/python"

To explain the example above, if you instantiate a path class pathlib.Path() without any arguments it will use . as default value, which refers to the current working directory. So the first two examples both resolve to /home/python.

foo/bar.txt is a relative path. If your working directory is /home/python it will resolve to the absolute path /home/python/foo/bar.txt. If you are in the working directory /root it will resolve to /root/foo/bar.txt.


pathlib.Path().parent is another path object representing the parent of the path given.

# In working directory /root
In: pathlib.Path("/home/python").parent
Out: PosixPath("/home")

In: pathlib.Path("/home/python").parent.resolve()
Out: "/home"

# In working directory /home/python
In: pathlib.Path("foo").parent
Out: PosixPath(".")

In: pathlib.Path("foo").parent.resolve()
Out: "/home/python"

Yes your script will still run in other directories if you watch out for certain things.

# /home/python/foo.py

print(pathlib.Path().resolve())

Running this script from the directory /home/python will result in a path like this /home/python.

If you run the script from /home like this python/foo.py it will result in a path like this /home

If you watch out for potholes like this you should be fine to run your script from any directory. Doing mistakes here usually results in file not found errors.

like image 68
ShadowCrafter_01 Avatar answered Nov 02 '25 03:11

ShadowCrafter_01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!