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.

0

1 Answer 1

3

You can use pathlib:

from pathlib import Path path = Path(__file__).resolve().parents[2].joinpath("data\\external\\random_pages\\file.txt") 
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't know about the parents attribute!! Thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.