Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - 如何在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?

(正确的跨平台方法是什么?)

  ask by Nathan Osman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...