222

I have a little problem with ~ in my paths.

This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory.

my_dir = "~/some_dir"
if not os.path.exists(my_dir):
    os.makedirs(my_dir)

Note this is on a Linux-based system.

0

3 Answers 3

373

You need to expand the tilde manually:

my_dir = os.path.expanduser('~/some_dir')
0
88

The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.

In Python, this feature is implemented by os.path.expanduser:

my_dir = os.path.expanduser("~/some_dir")
3
  • Indeed, and it is perfectly valid to have a file or directory named ~. So the shell home shortcut is ambiguous and best avoided if you can.
    – bobince
    Jan 13, 2010 at 14:44
  • 8
    Note that one CAN access a file/dir named "~" in the current directory even when tilde expansion is occuring, using the "./~" notation. That works because ~ expansion only occurs at the start of a file name. It's also a convenient hack for file names starting with "-" or other characters that are treated specially by command line interfaces. You could tell I have probably done way too much shell script hacking.
    – ddaa
    Jan 13, 2010 at 21:30
  • The file system does not know anything about it. +1
    – Bin
    Dec 25, 2015 at 17:28
16

That's probably because Python is not Bash and doesn't follow same conventions. You may use this:

homedir = os.path.expanduser('~')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.