Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Pathlib alternate for os.path.join?

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") 
like image 299
reinhardt Avatar asked Apr 20 '20 11:04

reinhardt


People also ask

Does Pathlib replace os path?

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!

Why is Pathlib better than os path?

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?

Should I use os or Pathlib?

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.

Is Pathlib newer than os?

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.


Video Answer


1 Answers

Yes there is:

env_path = Path(__file__).parent / ".env" 

/ is all you need. This will work in different OSs

like image 155
quest Avatar answered Sep 20 '22 07:09

quest