'Import module from subfolder in Python [duplicate]
I want to import modules from subfolers in Python. It works from main.py to the subfolder, but not from subfolder to subfolder. Every folder has a __init__.py
This is how the folder structure looks like: Folder structure
I've created a little "class diagram", to show how it needs to be imported: Class diagram
main.py:
#! /usr/bin/env python
import os
from dotenv import load_dotenv
from os import path
from parser.Nfdump import Nfdump
def main():
load_dotenv()
p = Nfdump(os.getenv('flow_file_location'))
p.Parse()
if __name__ == "__main__":
main()
Nfdump.py
#! /usr/bin/env python
from types.Flow import Flow
from typing import NamedTuple
import ipaddress
class Nfdump:
def __init__(self, file_location):
self.file_location = file_location
def Parse(self):
##parsing magic
Flow.py:
#! /usr/bin/env python
from typing import NamedTuple
import ipaddress
class Flow(NamedTuple):
ip_source: ipaddress.ip_address
port_source: int
ip_dest: ipaddress.ip_address
port_dest: int
flags: str
Error thrown:
ModuleNotFoundError: No module named 'types.Flow'; 'types' is not a package
I am using Python 3 (3.10.2)
Solution 1:[1]
I think you should use relative imports. If I'm reading your hierarchy correctly, maybe the following:
In main:
from .parser.Nfdump import Nfdump
In Nfdump:
from ..types.Flow import Flow
The single dot means "one on the same level in the module hierarchy" and double dot means "one level up".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karl Knechtel |
