python get the path of the current file

Python is often used to write logs. Sometimes, when ignored, the path to obtain the file is the working path, not the absolute path, which leads to various errors. Record it here for future reference.

1. Get the working path

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os

print os.getcwd() 

If the script is executed in the current directory, such as directly executed in ide, it will output C:\py\01.py

If executed in other environments, such as python \py\01.py, the output is not C:\py\01.py, but "current working directory\01.py"

So logging, etc., cannot use os.getcwd()

 

2. Get the absolute path of the script

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os

filename = os.path.realpath(__file__)#C:\py\01.py
print os.path.dirname(filename)#C:\py\

At this time, whether the script is executed in the current directory or another directory, the correct absolute path can be obtained.

Commonly used splicing paths can be written like this

os.path.join(os.path.dirname(os.path.realpath(__file__)), 'log')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325426121&siteId=291194637