1

I'm working on a project that has this structure:

  1. src/
  2. data/ with csv and txt files
  3. mod/ with python classes
  4. main.py

classes in mod/ use read csv to get data in form of

class Currency:
    def __init__(self, country_name: str):
        self.country = country_name
        self.code = self.get_code()

    def get_code(self) -> str:
        with open("../data/iso-4217.csv") as file:
            country_list = list(csv.reader(file))
            for row in country_list[1:]:
                if row[0] == self.country:
                    code = row[1]
        return code

And it works just fine. But whenever I import the class itself to main.py, I get FileNotFoundError: [Errno 2] No such file or directory: '../data/iso-4217.csv'

Is there a way to make correct import using relative pathing?

Using absolute pathing seems to fix the issue, but i'd rather use relative

jarmod
  • 71,565
  • 16
  • 115
  • 122
Kraioshi
  • 11
  • 2
  • 1
    You can't use relative pathnames unless you know where the script is going to be executed (its current working directory) – DarkKnight Jun 12 '23 at 10:27
  • 1
    It seems that you want to open a file using a path that it relative to the location of the Python script. See https://stackoverflow.com/questions/7165749 – Stephen C Jun 12 '23 at 10:59
  • (The problem is nothing to do with importing classes. You are not getting the problem in the import statement. You are getting it when you execute some code (after the import) that is attempting to open a file using a relative path. This will be evident from the stack trace. If you think more clearly about what is going on, it will be easier to work out how to solve the problem.) – Stephen C Jun 12 '23 at 11:00

1 Answers1

1

Try replacing "../data/iso-4217.csv" by "data/iso-4217.csv" as you are working in the main.py directory's.

Yet another option is to send the relative path in a variable to make the class usable from anywhere.