Home > Article > Backend Development > Share the errors you encountered when writing python
I wrote some code today. I originally wanted to get the three directories above the current file, but the result was an error.
import osimport sysprint(__file__)# 得到上上层目录的路径之后,加入到默认的环境变量中BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) sys.path.append(BASE_DIR)print("******", BASE_DIR) 输出结果:<encoding error> ******
Then I saw the following statement in Stack Overflow
The general meaning of the above is that dirname and basename will not consider the current path when dividing the path, so we need to make the following modifications, but a program I wrote before uses It's the same code and can be executed. This makes me confused, but the problem is indeed solved. If any kind-hearted netizen knows the specific reason, please give me some advice in the comments below
Modify the code: change __file__ to os.path.abspath(__file___)
import osimport sysprint(os.path.abspath(__file__)) # 得到上上层目录的路径之后,加入到默认的环境变量中BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(BASE_DIR)print("******", BASE_DIR)
The above is the detailed content of Share the errors you encountered when writing python. For more information, please follow other related articles on the PHP Chinese website!