This question already has an answer here:
(这个问题已经在这里有了答案:)
(如何使用python查找真实的用户主目录?)
(9个答案)
I need to get the location of the home directory of the current logged-on user.
(我需要获取当前登录用户的主目录的位置。)
(目前,我一直在Linux上使用以下命令:)
os.getenv("HOME")
However, this does not work on Windows.
(但是,这在Windows上不起作用。)
(正确的跨平台方法是什么?)
You want to use os.path.expanduser .
(您要使用os.path.expanduser 。)
(这将确保它可以在所有平台上运行)
from os.path import expanduser home = expanduser("~")
If you're on Python 3.5+ you can use pathlib.Path.home() :
(如果您使用的是Python 3.5+,则可以使用pathlib.Path.home() :)
from pathlib import Path home = str(Path.home())
1.4m articles
1.4m replys
5 comments
56.9k users