I am currently accessing the parent directory of my file using Pathlib
as follows:
Path(__file__).parent
When I print it, and this gives me the following output:
print('Parent: ', Path(__file__).parent) #output /home/user/EC/main-folder
The main-folder
has a .env
file which I want to access and for that I want to join the parent path with the .env
. Right now, I did:
dotenv_path = os.path.join(Path(__file__).parent, ".env")
which works. But I would like to know, if there is a Pathlib
alternate to os.path.join()
? Something like:
dotenv_path = pathlib_alternate_for_join(Path(__file__).parent, ".env")
The pathlib module replaces many of these filesystem-related os utilities with methods on the Path object. Notice that the pathlib code puts the path first because of method chaining!
Pathlib allows you to easily iterate over that directory's content and also get files and folders that match a specific pattern. Remember the glob module that you used to import along with the os module to get paths that match a pattern?
Of course, we still need to know how to use the OS library as it is one of the most powerful and basic libraries in Python. However, when we need some file system operations in typical scenarios, it is highly recommended to use Pathlib.
pathlib was introduced in Python 3.4 and offers a different set of abstractions for working with paths. However, just because it is newer, that doesn't mean it's better.
Yes there is:
env_path = Path(__file__).parent / ".env"
/
is all you need. This will work in different OSs
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