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

  • use `pathlib` or `os.path` – imperosol Apr 06 '22 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. – Mike Scotty Apr 06 '22 at 11:44
  • 1
    in which folder is your python script located? and how are you running it? –  Apr 06 '22 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')`. – ekhumoro Apr 06 '22 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 – honkaisenbai Apr 06 '22 at 13:13

1 Answers1

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())