FileNotFoundError在导入读取CSV文件的类时发生。

huangapple go评论65阅读模式
英文:

FileNotFoundError while importing class that reads csv

问题

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.

英文:

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

答案1

得分: 1

尝试将"../data/iso-4217.csv"替换为"data/iso-4217.csv",因为您正在main.py目录中工作。

另一个选项是将相对路径发送到变量中,以使该类可以从任何位置使用。

英文:

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.

huangapple
  • 本文由 发表于 2023年6月12日 18:24:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定