Home > Blockchain >  How to use relative paths
How to use relative paths

Time:02-03

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related