如何在Python中获取主目录? [英] How to get the home directory in Python?

查看:213
本文介绍了如何在Python中获取主目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")

但是,这在Windows上不起作用.跨平台的正确方法是什么?

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

推荐答案

您要使用

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

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

如果您使用的是 Python 3.5 + ,则可以使用 pathlib.Path.home():

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

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

这篇关于如何在Python中获取主目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆