Python でカレントユーザのホームディレクトリのパスを取得する方法をご紹介します。
Python でカレントユーザのホームディレクトリを取得するには os.path.expanduser() 関数を使うのが便利です。
import os.path
print(os.path.expanduser('~'))
# => /Users/ユーザー名
print(os.path.expanduser('~/.bashrc'))
# => /Users/ユーザー名/.bashrc公式のドキュメントには以下のように説明されています。
On Unix, an initial
~is replaced by the environment variableHOMEif it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in modulepwd. An initial~useris looked up directly in the password directory.On Windows,
HOMEandUSERPROFILEwill be used if set, otherwise a combination ofHOMEPATHandHOMEDRIVEwill be used. An initial~useris handled by stripping the last directory component from the created user path derived above.Unix では、先頭の
~は、環境変数HOMEが設定されているならその値に置き換えられます。そうでなければ、現在のユーザのホームディレクトリをビルトインモジュールpwdを使ってパスワードディレクトリから探して置き換えます。先頭の~userについては、直接パスワードディレクトリから探します。Windows では
~だけがサポートされ、環境変数HOMEまたはHOMEDRIVEとHOMEPATHの組み合わせで置き換えられます。
便利ですねー。