Possible Duplicate:
How to find the real user home directory using python?
How to get the home directory in Python?
我想访问 /home/weasel
以从那里读取一些文件,但我当然不想写完整路径 - 所以其他用户可以使用脚本.. 你怎么样在 Linux 上使用 python 知道您的用户名或主目录吗?
谢谢
最佳答案
要在 python 中获取 homedir,可以使用 os.path.expanduser('~')
.
这也适用于较长路径的一部分,例如 os.path.expanduser('~/some/directory/file.txt')
。如果路径中没有~,则函数将返回路径不变。
所以取决于你想做什么,它比阅读 os.environ['HOME']
用户名可通过 getpass.getuser()
获得
关于python - 在 Python 中找到 "home directory"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10170407/