0

Im use this path to go back 1 directory (back to directory 'dsa')

with open('../file.txt','r',encoding='utf-8') as f: print(f.read()) 

I get this error

Traceback (most recent call last): File "c:\Users\Secret\Desktop\Code\dsa\main.py", line 1, in <module> with open('../file.txt','r',encoding='utf-8') as f: FileNotFoundError: [Errno 2] No such file or directory: '../file.txt' 

my version of Python is 3.10.2

5
  • use pathlib or os.path Commented Apr 6, 2022 at 11:44
  • 1
    but ... according to the error you're already in dsa? That being said, it's usually safer to build an absolute path instead of relying on relative paths. Depending on how you start your app, the CWD might not be what you hope/expect it to be. Commented Apr 6, 2022 at 11:44
  • 1
    in which folder is your python script located? and how are you running it? Commented Apr 6, 2022 at 11:46
  • 1
    What you're really asking is how to get a path relative to the current script. So that would be: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'file.txt'). Commented Apr 6, 2022 at 11:49
  • I run a code in folder dsa, folder dsa in folder Code and folder Code in my Desktop. File file.txt is in folder Code But when I run code in folder Code and file file.txt in my Desktop. It's working Commented Apr 6, 2022 at 13:13

1 Answer 1

0

You can use the built in pathlib.Path to get the relative paths you need:

from pathlib import Path cwd = Path.cwd() parent = cwd.parent file = parent / 'file.txt' # '/' operator joins string to Path with open(file, 'r', encoding='utf-8') as f: print(f.read()) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.