2

I am working with a few nested folders, and I have trouble accessing some of the folders from my current working directory.I am currently working on this in Python 3.6

Here is the current file directory structure:

../PROJECT
../PROJECT/REVIEWS/RESULTS/excel_file.xlsx
../PROJECT/LDA_MODEL/TOPIC_MODEL/model.py

If my current working directory is ../PROJECT/LDA_MODEL/TOPIC_MODEL, how can I access the /PROJECT/REVIEWS/RESULTS/excel_file.xlsx without changing my current working directory?

Ayman Nedjmeddine
  • 11,521
  • 1
  • 20
  • 31
Matthew Soh
  • 133
  • 1
  • 7
  • Have you tried using `..` to refer to the parent directory? E.g. the path `Dir/Child/../` refers to the directory `Dir` – akraf Nov 30 '18 at 08:48
  • You can just do `filepath = "../PROJECT/REVIEWS/RESULTS/excel_file.xlsx"` Note: Filepath should be from the root. – Hayat Nov 30 '18 at 08:49

1 Answers1

4

You can easily do so using os.path

If your current working directory is ../PROJECT/LDA_MODEL/TOPIC_MODEL/, then you can try this:

import os
my_dir = os.path.abspath(os.path.join("..", "..", "REVIEWS", "RESULTS", "excel_file.xlsx"))
  • os.path.abspath will return to you the absolute pas to the path you're looking for.
  • os.path.join will create a path respecting your OS' path structure ("\" on Windows vs "/" on Linux for example). It's usually safer than typing yourself. In this case, on Windows, the os.path.join will return "..\\..\\REVIEWS\\RESULTS\\excel_file.xlsx".
  • ".." means you go one directory UP.

If you need to access a file using an absolute path, start your os.path.join with "/"

import os
my_dir = os.path.abspath(os.path.join("/", "MY", "PATH", "TO", "MY", "FILE"))

Again, it will depend on your OS, but on Windows this will return: "C:\\MY\\PATH\\TO\\MY\\FILE\\"