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 variableHOME
if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in modulepwd
. An initial~user
is looked up directly in the password directory.
On Windows,HOME
andUSERPROFILE
will be used if set, otherwise a combination ofHOMEPATH
andHOMEDRIVE
will be used. An initial~user
is handled by stripping the last directory component from the created user path derived above.
Unix では、先頭の~
は、環境変数HOME
が設定されているならその値に置き換えられます。そうでなければ、現在のユーザのホームディレクトリをビルトインモジュールpwd
を使ってパスワードディレクトリから探して置き換えます。先頭の~user
については、直接パスワードディレクトリから探します。
Windows では~
だけがサポートされ、環境変数HOME
またはHOMEDRIVE
とHOMEPATH
の組み合わせで置き換えられます。
便利ですねー。
参考
linux - How to find the real user home directory using python? - Stack Overflow
10.1. os.path — Common pathname manipulations — Python 2.7.10 documentation
10.1. os.path — 共通のパス名操作 — Python 2.7ja1 documentation
2 件のコメント:
Good!!欲しい情報でした。
bird kiwi さん、コメントいただきありがとうございます :)
コメントを投稿