2022/11/18 新增方法2,更加简单,并且兼容性更好。
代码段,便于快速复制
import os
import sys
import pathlib
def get_home_dir_2():
'''
获得当前用户家目录,支持windows,linux和macosx
更新方法,更加简单
:return:
'''
homedir = str(pathlib.Path.home())
return homedir
def get_home_dir():
'''
获得家目录
:return:
'''
if sys.platform == 'win32':
homedir = os.environ['USERPROFILE']
elif sys.platform == 'linux' or sys.platform == 'darwin':
homedir = os.environ['HOME']
else:
raise NotImplemented(f'Error! Not this system. {sys.platform}')
return homedir
print(get_home_dir())
跨平台获取用户家目录的简洁方法
这篇博客介绍了在Python中使用`pathlib`模块的`Path.home()`方法,实现了一个兼容Windows、Linux和macOS的获取用户家目录的简单函数`get_home_dir_2()`。相较于传统的根据操作系统平台条件判断的方法,新方法更简洁易读。
744

被折叠的 条评论
为什么被折叠?



