Python project, if the Pyton code needs to access an external file that is located in a relative path to the code file, we can use a relative path in the code to access the file. For example, the code structure in the diagram:
sample.py file, if you want to access the configuration file Server.ini file, you can use the. /conf/server.ini "for access.
But often the problem is that the Python file is referenced by the other directory's Python file import, where the relative path is wrong. This is because the relative path is computed based on the path of the currently running script, and the relative path is invalidated if the referenced Python file and the calling file are not in the same directory.
For example, in our example, the sample.py file reads as follows:
Import configparser
import OS
def read_conf ():
file_path = '. /conf/server.ini '
config = configparser.configparser ()
config.read (file_path) return
config.get (' Conf ', ' value ')
if __name__ = = ' __main__ ':
print read_conf ()
main.py contents are as follows:
From utils.sample import read_conf
print read_conf ()
For example, in the previous illustration, if main.py calls read_conf, it will find that the Server.ini file is not found. The problem is that when you run main.py, the current path is the folder where the main.py resides, and the relative path used in sample.py is based on the folder and the wrong location is found. The solution is to use the file absolute path in sample.py to access the Server.ini file, but we have to get the runtime path based on the current location of the script. This time we need to use the __file__ variable in python, the built-in variable that holds the current path information for this Python file, according to which we can os.path.dirname (__file__) The absolute path of the corresponding file.
In sample.py, the File_path variable is modified as follows:
File_path = '.. /conf/server.ini '
-->
file_path = Os.path.join (Os.path.dirname (__file__) + '/. /conf/server.ini ')
Note that the path is added '/' before the file path is incomplete.
Resources:
http://stackoverflow.com/questions/918154/relative-paths-in-pythonhttp://stackoverflow.com/questions/1270951/ Python-how-to-refer-to-relative-paths-of-resources-when-working-with-code-repo