All I want in python 3 is to use a relative path on a win 10 PC. like:
open('folder_for_text\text_subfolder\myText.txt')
I've tried:
open('folder_for_text/text_subfolder/myText.txt') # this should also work in python
open('folder_for_text\\text_subfolder\myText.txt')
open(r'folder_for_text\text_subfolder\myText.txt')
and every frickin' library on this planet
Somebody help me, please!
wjandrea
34k10 gold badges69 silver badges107 bronze badges
-
2What error is your code raising for each of this options? Where in this relative path is your code running?olenscki– olenscki2020年06月18日 16:13:54 +00:00Commented Jun 18, 2020 at 16:13
-
1if you are using relative paths, make sure it is the relative path from where you are running the script and not where the script is located.Dorian– Dorian2020年06月18日 16:17:28 +00:00Commented Jun 18, 2020 at 16:17
-
All of your backslashes must be doubled up, not just the first one.Mark Ransom– Mark Ransom2020年06月18日 16:49:10 +00:00Commented Jun 18, 2020 at 16:49
-
Welcome to SO! Check out the tour. Debugging questions require a minimal reproducible example, but you haven't even said what the problem is. If there's an error, please provide it in full. You can edit the post. See How to Ask for more advice.wjandrea– wjandrea2020年06月18日 16:50:59 +00:00Commented Jun 18, 2020 at 16:50
1 Answer 1
If you are running the script from a different folder, the relative path must be from the place where you are running the script:
e.g. if the script is in Documents and you are running it from your home folder like
python Documents/script.py
the relative path needs to be from the home folder, not from the script location.
Also make use of the os.path package. this alows you to build operating system agnostic code with paths:
rel_path = os.path.join('..', 'dir1', 'dir2', 'file.txt')
answered Jun 18, 2020 at 16:20
Dorian
1,4882 gold badges14 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Mark Ransom
Note that
os.getcwd() will show you the current base directory no matter where or how you started the script.lang-py