How to find the real user home directory using Python?

Posted in :

在 macOS 的 python 裡直接輸入 ~/Documents/ 這個路徑,是無效的,檢查 path.exists 是 false. 解法:

import os
print(os.path.expanduser('~'))

You can also query the environment variables for the HOME variable −

import os
print(os.environ['HOME'])

If you’re on Python 3.4+, you can also use pathlib module to get the home directory. 

example

from pathlib import Path
print(Path.home())

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *