如何在Python中获取主目录?

问题:如何在Python中获取主目录?

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

os.getenv("HOME")

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

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

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


回答 0

您要使用os.path.expanduser
这将确保它可在所有平台上运行:

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

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

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

You want to use 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():

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

回答 1

这是一种Linux方式cd ..如果您需要使用它,请注意:(如果位于子目录中,它将进入该目录)

Here is a linux way cd .. if you need to use that instead note:(if you are in a sub directory then it will take to the directory)