Why does `os.listdir` does not accept a path with "~"?

Viewed 82

When using python if you have say:

dd="~/this/path/do/exist/"

and you do

os.listdir(dd)

you get

FileNotFoundError: [Errno2] no such file or directory '~/this/path/do/exist/'

even though the path exists.

Why is this and how can it be corrected?


Furthermore if you pass a path with ~ using argparse it gets converted to a full path and this problem does not occur.

1 Answers

~ is interpreted by the shell, which is why it works when you use it on the command line via argparse.

Use os.path.expanduser to evaluate ~.

import os
os.path.expanduser("~/this/path/do/exist/")

If you are using pathlib.Path, you can use Path.expanduser().

from pathlib import Path
Path("~/this/path/do/exist/").expanduser()
Related