找到“主目录"在Python中? [英] Find "home directory" in Python?
问题描述
Possible Duplicate:
How to find the real user home directory using python?
How to get the home directory in Python?
我想访问/home/weasel
从那里读取一些文件,但是我当然不想写完整的路径-所以其他用户可以使用该脚本. Linux上的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?
谢谢
推荐答案
To get the homedir in python, you can use os.path.expanduser('~')
.
如果它是较长路径的一部分(例如os.path.expanduser('~/some/directory/file.txt')
),则也可以使用.如果路径中没有〜,则函数将返回不变的路径.
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.environ['HOME']
So depending on what you want to do it's better than reading os.environ['HOME']
这篇关于找到“主目录"在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!