1

I want to open/read/write a file(s) which is located in a folder in the parent directory:

This is my file tree:

HiLo v2.00/
┣ Data/
┣ Files/
┃ ┣ __pycache__/
┃ ┃ ┣ __init__.cpython-38.pyc
┃ ┃ ┣ config.cpython-38.pyc
┃ ┃ ┣ menu.cpython-38.pyc
┃ ┃ ┗ score.cpython-38.pyc
┃ ┣ __init__.py
┃ ┣ config.py
┃ ┣ game.py
┃ ┣ menu.py
┃ ┗ score.py
┣ __pycache__/
┃ ┣ config.cpython-38.pyc
┃ ┣ game.cpython-38.pyc
┃ ┗ score.cpython-38.pyc
┗ setup.py

I want to open/read/write files in Data/ folder. How would I open it from Files/menu.py?

1 Answers1

2

this sounds like what you are looking for Get parent of current directory from Python script

along with https://stackabuse.com/introduction-to-the-python-pathlib-module/

from pathlib import Path
d = Path(__file__).resolve().parents[1]
print(d)
d = d / 'Data' / 'yourfile.txt'
print(d)
with d.open() as file:
    print(file.read())
Prophacy
  • 108
  • 8