Search code examples
pythonmacospython-os

Chdir to ~/Library on Mac is returning an error, regardless of current directory


My code:

import os
os.chdir("~/Library")

The error:

raceback (most recent call last):
  File "/Users/user/PycharmProjects/untitled/tree_creation.py", line 13, in <module>
    os.chdir("~/Library")
FileNotFoundError: [Errno 2] No such file or directory: '~/Library'

I tried:

import os
os.chdir("/Users")
os.chdir("~/Library")

but that returned the same error. The ~/Library directory does exist(I think), since I was able to navigate to it with go to file.

What's going on?

Thank you!


Solution

  • ~ is not automatically converted to a path. You can convert it using os.path.expanduser.

    os.chdir(os.path.expanduser('~/Library'))