SoFunction
Updated on 2024-11-13

Several ways to import Python parent directory files

How does this import files from Python's parent directory? [ ]

Suppose there is the following catalog:

-python

----file1

---------file1_1

------------------pfile1_1.py

---------

----file2

---------

----

----

What should I do if I want to import the file in pfile1_1.py?

The first and simplest method

Mark the parent file directory as: the root directory of the source code.

The second simple solution

Just set all from and import to absolute paths.

There is a third way if you don't want to change the code.

The third, relative references

…/
You can use relative references as the existence of the package, if you run it directly will report an error, this error is the most commonly encountered error, to put it simply is because you run the current file as the main program, then the current file where the folder is not a python package, since it's not a package you're looking for it in the upper level of the use of ... directory, naturally you can't find it, because it's not a package. What to do about this? The solution is simple:
If you define a separate or file and run it from there, then the folder where the package is located is a python package, so naturally there is a layer above it, and you can use relative references. However, you must remember to import the package with an absolute path, or you will make the same mistake as above.

from …kmeans.kmeans_handwrite import *

Fourth, first add its parent directory to the system directory

import sys
('/home/zikang/python/')

Importing is

import pfile

Importing is

from file1 import pfile2

Naturally, when importing any .py file, you just need to use the

('The absolute path where the file is located')

Add the absolute path of the file to the system path, and then import it in the same level or lower level directory.

summarize

to this article on the Python upper directory file import several methods of introduction to this article, more related to Python upper directory file import content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!