0

I am using the cookie cutter data science project model (https://drivendata.github.io/cookiecutter-data-science/) and would like to open a file in a different directory from my script, read the file, and then create/write a new file to a different directory from my script. I would like this to work no matter what computer the folder is on (in other words, I can't hard code the absolute path).

I know that some questions already pertain to this issue, but the resulting answers have not worked. I have mostly been looking at os and pathlib. Solutions I have attempted include but are not limited to the ones found at these questions: Open File in Another Directory (Python) and Open file in a relative location in Python.

Below is the relevant parts of the structure of the project:

Project
|--data
|    |--external
|    |   --file.txt
|        |--random_pages
|--src
|    |--data
|        --script.py

I'd like to use script.py to read file.txt, then create a file in random_pages.

Liz W.
  • 35
  • 7

1 Answers1

3

You can use pathlib:

from pathlib import Path

path = Path(__file__).resolve().parents[2].joinpath("data\\external\\random_pages\\file.txt")
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35