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 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 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 runed in different folders in different operation systems.

4 Answers4

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
  • 400
  • 3
  • 10
0

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

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
  • 191
  • 2
  • 10
0

I found the answer. the key is using "." for importing upper hand directories. more info on using '.' for module import is here: What does a . in an import statement in Python mean?

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31902691) – Emi OB Jun 01 '22 at 08:07