大家好,我是雄雄,欢迎关注微信公众号:雄雄的小课堂
今天介绍一下,如何在python中获取当前项目所在的目录,而不是运行脚本的目录。
class ProjectPaths:# 初始化时获取当前脚本的路径@staticmethoddef get_script_dir():current_path = sys.path[0]return current_path# 读取词云的路径
FILE_PATH = ProjectPaths.get_script_dir() + '/ciyun/'
# 生成词云路径
CIYUN_PATH = ProjectPaths.get_script_dir() + '/ciyun/'
# 项目路径
LOG_PATH = ProjectPaths.get_script_dir() + '/damoxing/'
# 其他文件的路径
PROJECT_PATH = ProjectPaths.get_script_dir()+"/"
然后我们在别的python
文件中就可以直接通过代码使用了,代码如下:
def get_json(key: str):if not os.path.exists(LOG_PATH + 'csv_data/zp_token.json'):with open(LOG_PATH + "csv_data/zp_token.json", "w", encoding='utf-8') as f:json.dump({'accessToken': '','refreshToken': 'eyJhbGc'},f)f.close()with open(LOG_PATH + "csv_data/zp_token.json", "r", encoding='utf-8') as f:user_dic = json.load(f)f.close()if key in user_dic:return user_dic[key]else:return None