1

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)

4
  • What did you try? Hint: it'll just work, relative to the folder you're in when you run the script. Commented Feb 3, 2023 at 13:58
  • If the Python script and text document are in the same folder, you don't need a path: just use r"textfile.txt" Commented Feb 3, 2023 at 13:59
  • You can use ../textfile.txt Commented Feb 3, 2023 at 13:59
  • I tried to write "textfile.txt" and "../textfile.txt", but it didn't work Commented Feb 3, 2023 at 14:31

3 Answers 3

2

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

0
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 

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.