如何在Python中获取主目录? [重复]

本文翻译自:How to get the home directory in Python? [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

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. 但是,这在Windows上不起作用。 What is the correct cross-platform way to do this? 正确的跨平台方法是什么?


#1楼

参考:https://stackoom.com/question/Gu6K/如何在Python中获取主目录-重复


#2楼

You want to use os.path.expanduser . 您要使用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() : 如果您使用的是Python 3.5+,则可以使用pathlib.Path.home()

from pathlib import Path
home = str(Path.home())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值