`os.listdir` 为 `~` 抛出 Error2

`os.listdir` throws Error2 for `~`

python 版本: 3.8 OS:Manjaro KDE

当我调用 os.listdir('/home/user_name') 时,它工作正常。

但是,当我调用 os.listdir('~') 时,它抛出了 FileNotFoundError: [Errno 2] No such file or directory: '~'

为什么os.listdir没看懂~

It's a Bash feature called "tilde expansion". It's a function of the shell, not the OS.

因此,python的os包无法识别~

你可以这样使用它:

p = os.path.expanduser('~')
os.listdir(p)

您可以参考这些链接:

Python's os.makedirs doesn't understand “~” in my path

From documentation