Search code examples
pythonwindowsrelative-path

How to use relative paths


I recently made a small program (.py) that takes data from another file (.txt) in the same folder.

Python file path: "C:\Users\User\Desktop\Folder\pythonfile.py"

Text file path: "C:\Users\User\Desktop\Folder\textfile.txt"

So I wrote: with open(r'C:\Users\User\Desktop\Folder\textfile.txt', encoding='utf8') as file

And it works, but now I want to replace this path with a relative path (because every time I move the folder I must change the path in the program) and I don't know how... or if it is possible...

I hope you can suggest something... (I would like it to be simple and I also forgot to say that I have windows 11)


Solution

  • If you pass a relative folder to the open function it will search for it in the loacl directory:

    with open('textfile.txt', encoding='utf8') as f:
        pass
    

    This unfortunately will only work if you launch your script form its folder. If you want to be more generic and you want it to work regardless of which folder you run from you can do it as well. You can get the path for the python file being launched via the __file__ build-in variable. The pathlib module then provides some helpfull functions to get the parent directory. Putting it all together you could do:

    from pathlib import Path
    
    with open(Path(__file__).parent / 'textfile.txt', encoding='utf8') as f:
        pass