Skip to main content
 首页 » 编程设计

python之如何使用 Python 打开 "~/.bash_profile"

2025年05月04日15soundcode

我想使用 Python 来编辑 ~/.bash_profile,但是当我运行这些代码时:

f = open('~/.bash_profile', 'rb') 

它告诉我:

IOError: [Errno 2] No such file or directory: '~/.bash_profile' 

我认为这是因为 ~/.bash_profile 是一个系统保护文件。 有什么方法可以用 Python 打开这个文件吗?

请您参考如下方法:

通常 ~ 由 shell 扩展,而不是由系统调用扩展。在 Python 中,使用 os.path.expanduser()扩展以 ~ 开头的路径。