找到“主目录"在Python中? [英] Find "home directory" in Python?

查看:81
本文介绍了找到“主目录"在Python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何使用python查找真实用户的主目录?
如何在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?

谢谢

推荐答案

要在python中获取homedir,可以使用

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']

可通过 getpass.getuser()

这篇关于找到“主目录"在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆