directory organization
There are already some agreed-upon directory structures on how to organize a good Python project directory structure. In this question on Stackoverflow , you can see everyone talking about the Python directory structure.
Assuming your project is named foo, the most convenient and quick directory structure I suggest is enough:
Foo/
|-- bin/
| |-- foo
|
|--conf/
| |--__init__.py
| |--settings.py
|
|-- foo/
| |-- tests/
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py
| |-- main.py
|
|-- docs/
| |-- conf.py
| |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README
Briefly explain:
bin/
: Store some executable files of the project, of course, you can namescript/
it and so on.- conf/: store the project configuration file
foo/
: holds all the source code of the project. (1) All modules and packages in the source code should be placed in this directory. Don't put it in the top-level directory. (2) Its subdirectorytests/
stores unit test code; (3) The entry of the program is best namedmain.py
.docs/
: Store some documents.setup.py
: Scripts for installation, deployment, packaging.requirements.txt
: A list of external Python packages that store software dependencies.README
: Project description file.
In addition, there are some programs that give more content. For example LICENSE.txt
, ChangeLog.txt
files, etc., I did not list here, because these things are mainly used when the project is open source. If you want to write an open source software, how to organize the directory, you can refer to this article .
How to use files in different directories
The directory structure in the above figure is an example. In main.py, we use the files in the bin directory. First, we need to find the Foo/ directory, and then import the modules in the subdirectories under Foo/, and we need to obtain it automatically, and cannot write to death. At this time, the os module is used
import them
import sys
1. Find the absolute path of the file
os.path.abspath(__file__) #Get the absolute path of the file, including the file name
2. Get the directory of the file
os.path.dirname(os.path.abspath(__file__) ) # For example, the directory of main.py is foo/
3. Get the parent directory of the file directory again
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__) ))
4. Add to the environment variable
sys.path.append(BASE_DIR)
5. Import the required directory
①. import bin
②. from bin import *