英文:
FileNotFoundError while importing class that reads csv
问题
I'm working on a project that has this structure:
- src/
- data/ with csv and txt files
- mod/ with python classes
- 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:
- src/
- data/ with csv and txt files
- mod/ with python classes
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论