Home  >  Article  >  Backend Development  >  Share the errors you encountered when writing python

Share the errors you encountered when writing python

零下一度
零下一度Original
2017-06-30 09:28:481079browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn