简体   繁体   English

Python从子文件夹导入

[英]Python imports from subfolders

I am attempting to grade some python submissions that are in separate folders for each student. 我试图为每个学生在单独的文件夹中对一些python提交进行评分。 To do this, there is a function, say f() which I want to run. 要做到这一点,有一个函数,比如我想运行的f()。 I understand that if my current path is the same as the one where the file is located, I can simply do 我知道如果我当前的路径与文件所在的路径相同,我可以这样做

import filename
filename.f()

However, are there better ways? 但是,还有更好的方法吗? For instance, let's say the directory structure is as follows: 例如,假设目录结构如下:

main.py
student/run_this.py

I know that if there is a "__init__.py" file in the student folder, I can just type 我知道如果学生文件夹中有“__init__.py”文件,我可以输入

import student.run_this

However, without that file, it doesn't work. 但是,没有该文件,它不起作用。

Some similar questions I found were 我发现的一些类似问题

but none of these gave particularly satisfying answers. 但这些都没有给出特别令人满意的答案。

create an __init__.py module inside the folder student which should contain 在应该包含的文件夹student创建一个__init__.py模块

from . import *

You can then call any modules from student folder to its parent folder modules as 然后,您可以将学生文件夹中的任何模块调用到其父文件夹模块中

import student.module.py

If you post any other errors you are facing, we can help further. 如果您发布任何其他错误,我们可以提供进一步的帮助。

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

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