How to use relative paths

Question:

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

Python file path: "C:UsersUserDesktopFolderpythonfile.py"

Text file path: "C:UsersUserDesktopFoldertextfile.txt"

So I wrote: with open(r'C:UsersUserDesktopFoldertextfile.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)

Asked By: John Chr

||

Answers:

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
Answered By: Matteo Zanoni
import os

directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(directory, 'textfile.txt')

with open(file_path, encoding='utf8') as file:
    # and then the code here
Answered By: ProAslan

Using os, you can do something like

import os

directory = os.path.dirname(__file__)
myFile = with open(os.path.join(directory, 'textfile.txt'), encoding='utf8') as file
Answered By: Ibrahim Hisham
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.