Search code examples
pythonpathlib

Nicest way to find current directory of file in python


I'm looking for a replacement of

import os
package_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(package_dir,'foo.csv')

My working path isn’t the path of the file. So when I want to load a file, I need a way to generate the relative path compared to my working directory.

I want to update to pathlib (or whatever else is out there). But what is the nicest way to do the same?

I found https://stackoverflow.com/a/44188489, but I don't think this solution looks better than my current way.

Remark:

It's not a duplicate of How to properly determine current script directory?, since I explicitly asked about the nicest way. Most of the solutions in the other post don't look nice, or are already mentioned in the my question. The solution

Path(__file__).with_name("foo.csv")

given here is much better than the solutions given in the other question, since it's easy to understand, and a really pythonic way to solve it. If this question was a dublicate, on the other post an equally good answer would exist.


Solution

  • If you're looking to do the same with pathlib, it could look like this:

    from pathlib import Path
    
    package_dir = Path(__file__).parent.absolute()
    file_path = package_dir.joinpath("foo.csv")
    

    Unless you're changing current working directory, you may not really need/want to use .absolute().

    If you actually do not need to know what package_dir would be, you can also just get the file_path directly:

    file_path = Path(__file__).with_name("foo.csv").absolute()
    

    Which gives you new Path replacing the file name.