如何在Python中获取主目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4028904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:55:37  来源:igfitidea点击:

How to get the home directory in Python?

pythoncross-platformhome-directory

提问by Nathan Osman

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:

我需要获取当前登录用户的主目录的位置。目前,我一直在 Linux 上使用以下内容:

os.getenv("HOME")

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

但是,这在 Windows 上不起作用。执行此操作的正确跨平台方法是什么?

采纳答案by dcolish

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

你想使用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())