0

I have a python file in "mainDirectory/subdirectory/myCode.py" and in my code, I want to refer to a .csv file in "mainDirectory/some_data.csv" I don't want to use an absolute path since I run the code in different operating systems and using absolute path may make trouble. so in short, is there a way to refer to the upper directory of the current directory using a relative path in python?

I know how to refer to the subdirectories of the current directory using a relative path. but I'm looking for addressing to the upper-level directories using the relative path. I don't want to use absolute bath since the file is going to be run in different folders in different operating systems.

Update: I found one method here (it is not based on the relative path but it does the job): the key is using "." for importing upper hand directories. for example, one can access the same layer directory by using one dot. for accessing the one-layer higher, one can use two dots. in the above case, to access the "subdirectory" one can put this line in "myCode.py"

from .subdirectory import something

to access the "mainDirectory:

from ..mainDirectory import something

3 Answers3

1

If you look at the Python documentation, you will find that the language is not designed to be used like that. Instead you'll want to try to refactor your directories to put myCode.py in a parent level directory like mainDirectory.

mainDirectory
│   
└───myCode.py
│   
└───subdirectory
    │   
    │   some_data.csv

You are facing an issue with the nature of the PYTHONPATH. There is a great article on dealing with PYTHONPATH here:

https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html

It can be challenging if you're new to the language (or if you've been using it for years!) to navigate Python import statements. Reading up on PEP8 conventions for importing, and making sure your project conforms to standard language conventions can save you a lot of time, and a lot of messy git commits when you need to refactor your directory tree down the line.

0

You can always derive absolute path at run time using API provided by os package.

 import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

Complete answer was always a click away. Relative paths in Python

pankaj
  • 470
  • 5
  • 11
0

There are several tools in os.path that you can use:

from os.path import dirname
upper = dirname(dirname(__filepath__))

Here is alink to a more comprehensive answer on accessing upper directories: How do I get the parent directory in Python?

AlterV
  • 301
  • 1
  • 3
  • 10