0

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
asked Jun 18, 2020 at 16:12
4
  • 2
    What error is your code raising for each of this options? Where in this relative path is your code running? Commented Jun 18, 2020 at 16:13
  • 1
    if 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. Commented Jun 18, 2020 at 16:17
  • All of your backslashes must be doubled up, not just the first one. Commented 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. Commented Jun 18, 2020 at 16:50

1 Answer 1

2

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

1 Comment

Note that os.getcwd() will show you the current base directory no matter where or how you started the script.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.