简体   繁体   English

从其他文件夹导入模块(python)

[英]Import modules from different folder (python)

I have a folder, which contains two separate folders, one of which holds some python modules, and the other one holds a python script that uses those modules: 我有一个文件夹,其中包含两个单独的文件夹,其中一个包含一些python模块,另一个包含使用这些模块的python脚本:

parentFolder/
    lib/
       __init__.py
       readFile.py
       writeFile.py
    folder/
       run.py

The __init__.py file is empty. __init__.py文件为空。 In run.py , I have the following: run.py ,我有以下内容:

from ..lib import readFile

data = readFile('file.dat')

This gives me the error 这给我错误

Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from ..lib import readFile
ValueError: Attempted relative import in non-package 

What am I missing? 我想念什么?

You need to add __init__.py files (can be empty) to each of the directories to make them a package. 您需要将__init__.py文件(可以为空)添加到每个目录中,以使其成为一个包。 See the documentation for more details. 有关更多详细信息,请参见文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM