Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lấy thư mục home directory thật của user trong Python

Có nhiều cách cross-platform lấy home directory.

1. os.path.expanduser (cổ điển, mọi version)

import os
home = os.path.expanduser('~')
print(home)  # /home/user (Linux), C:\Users\user (Windows)

# Cũng dùng cho path con
docs = os.path.expanduser('~/Documents')

2. Environment variable

import os
home = os.environ.get('HOME')      # Unix
home = os.environ.get('USERPROFILE')  # Windows

3. pathlib.Path.home() (Python 3.5+, khuyến nghị)

from pathlib import Path
home = Path.home()
print(home)  # PosixPath('/home/user') hoặc WindowsPath('C:/Users/user')

So sánh

  • Path.home() — object-oriented, hiện đại, cross-platform tốt nhất.
  • expanduser('~') — tương thích ngược, dùng cho string path.
  • Env var — không tin cậy trên mọi env (cron, service...).