我想导入不同的文件夹作为模块。
我的文件夹结构是这样的:
/project
/movies
get_genres.py
/mysql
/movies
insert_genres.py
在我的
insert_genres.py
脚本中,我导入:
import movies.get_genres as moviegenres
def main():
for key, value in moviegenres.items():
print(key)
main()
我得到这样的错误:
import movies.get_genres as moviegenres
ModuleNotFoundError: No module named 'movies'
我在每个文件夹中打开了空的
__init__.py
文件,但是没有用。
您的文件夹结构未被识别为包,因为您的目录中没有任何 init.py 文件。需要 init.py 文件让 Python 知道该目录应该被视为一个包。
文件夹结构应该是这样的:
/project
/movies
__init__.py
get_genres.py
/mysql
/movies
__init__.py
insert_genres.py
在 /movies 和 /mysql/movies 文件夹中创建空的 init.py 文件。
更新 insert_genres.py 文件中的 sys.path 以包含父目录,以便 Python 可以找到电影包:
import sys
import os
# Add the parent directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import movies.get_genres as moviegenres
def main():
for key, value in moviegenres.items():
print(key)
main()