How to get the home directory in Python? [duplicate]

我的未来我决定 提交于 2019-11-26 01:09:50

问题


I need to get the location of the home directory of the current logged-on user. Currently, I\'ve been using the following on Linux:

os.getenv(\"HOME\")

However, this does not work on Windows. What is the correct cross-platform way to do this?


回答1:


You want to use os.path.expanduser. This will ensure it works on all platforms

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())


来源:https://stackoverflow.com/questions/4028904/how-to-get-the-home-directory-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!