-2

python version: 3.8 OS: Manjaro KDE

When I called os.listdir('/home/user_name'), it worked fine.

However, when I called os.listdir('~'), it threw FileNotFoundError: [Errno 2] No such file or directory: '~'.

Why os.listdir failed to understand ~?

2 Answers2

1

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

Thus, the os package of python does not recognize ~

Gaurav Agarwal
  • 611
  • 6
  • 18
1

You can use it like this :

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

You may refer these links :

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

From documentation

Atharva
  • 53
  • 1
  • 8