Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

When using python if you have say:

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

and you do

os.listdir(dd)

you get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

~ 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading