如何使用Python打开"〜/ .bash_profile"

Lan*_*ane 1 python .bash-profile

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

f = open('~/.bash_profile', 'rb')
Run Code Online (Sandbox Code Playgroud)

它告诉我:

IOError: [Errno 2] No such file or directory: '~/.bash_profile'
Run Code Online (Sandbox Code Playgroud)

我以为是因为~/.bash_profile是一个系统保护文件.有没有方法可以使用Python打开这个文件?

Ign*_*ams 6

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