简体   繁体   English

如何从父目录中的文件夹导入?

[英]How to import from a folder in a parent directory?

I want to import something from a file which is in a folder which is in the Parent Directory.我想从父目录中的文件夹中的文件中导入某些内容。

This is what the directory structure looks like.这就是目录结构的样子。

GAME
|--Player
|    `player.py  [FILE THAT NEEDS TO BE IMPORTED]
|--Story
|    `introduction.py [FILE NEEDS AN IMPORT STATEMENT]
|--mainGame.py

I know that to import player.py from the Player folder.我知道从 Player 文件夹中导入 player.py。 I need to do import Player.player , but I don't know how to navigate to a different folder in the parent directory.我需要做import Player.player ,但我不知道如何导航到父目录中的不同文件夹。

Please help.请帮忙。

Just need init .py file (blank file also work, no need to enter any code in this) in directory whose file you want to import.只需要在要导入的文件的目录中初始化.py 文件(空白文件也可以,无需在其中输入任何代码)。

so your directory structure will be like所以你的目录结构就像

GAME/
├── mainGame.py
├── Player
│   ├── __init__.py
│   └── player.py
└── Story
    └── introduction.py

and you can import by from Player import player or import Player.player .您可以通过from Player import playerimport Player.player

It's good to have all directory in package have init file so you can use it anywhere in project/package.最好让 package 中的所有目录都有 init 文件,这样您就可以在项目/包中的任何地方使用它。

for more information of python package, PYTHONPATH visit here , this (for basic of python packages) it's good blog to understand python project structure.有关 python package、PYTHONPATH 的更多信息,请访问此处(对于 python 包的基本知识)这是了解 python77 项目结构的好博客。

If GAME is a package (meaning it has an __init__.py file) then you can do import GAME.Story.introduction or import GAME.Player.player .如果 GAME 是 package (意味着它有一个__init__.py文件),那么您可以import GAME.Story.introductionimport GAME.Player.player

You can just add the __init__.py file to make it a package if it doesn't already have one.如果还没有,您可以添加__init__.py文件以使其成为 package。 It doesn't have to contain anything, it can just be a blank file.它不必包含任何内容,它可以只是一个空白文件。

Running packages can be a bit odd.运行包可能有点奇怪。 Running them from inside them doesn't work.从它们内部运行它们是行不通的。 To run it navigate to the directory above GAME and run the file you want to with python -m GAME.Story.introduction .要运行它,请导航到 GAME 上方的目录并使用python -m GAME.Story.introduction运行您想要的文件。 Otherwise I expect you will get a ModuleNotFoundError .否则我希望你会得到一个ModuleNotFoundError

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

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