Linux 在 Python 中找到“主目录”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10170407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find "home directory" in Python?
提问by WeaselFox
Possible Duplicate:
How to find the real user home directory using python?
How to get the home directory in Python?
I want to access /home/weasel
to read some files from there but I don't want to write the full path of course - so other users can use the script.. how do you know your username or your home dir with python on Linux?
我想/home/weasel
从那里读取一些文件,但我当然不想写完整路径 - 所以其他用户可以使用脚本..你如何知道你的用户名或你在 Linux 上使用 python 的主目录?
Thanks
谢谢
采纳答案by ThiefMaster
To get the homedir in python, you can use os.path.expanduser('~')
.
要在 python 中获取 homedir,您可以使用os.path.expanduser('~')
.
This also works if it's part of a longer path, such as os.path.expanduser('~/some/directory/file.txt')
. If there is no ~ in the path, the function will return the path unchanged.
如果它是较长路径的一部分,例如os.path.expanduser('~/some/directory/file.txt')
. 如果路径中没有~,函数将返回路径不变。
So depending on what you want to do it's better than reading os.environ['HOME']
所以取决于你想做什么,它比阅读更好 os.environ['HOME']
The username is available through getpass.getuser()
用户名可通过 getpass.getuser()
回答by Michael Wild
The portable way of getting the home directory in Python is using os.path.expanduser('~')
.
在 Python 中获取主目录的可移植方式是使用os.path.expanduser('~')
.