220

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Johan
  • 20,067
  • 28
  • 92
  • 110

3 Answers3

370

You need to expand the tilde manually:

my_dir = os.path.expanduser('~/some_dir')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
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")
ddaa
  • 52,890
  • 7
  • 50
  • 59
  • 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 '10 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 '10 at 21:30
  • `The file system does not know anything about it.` +1 – Bin Dec 25 '15 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('~')
gruszczy
  • 40,948
  • 31
  • 128
  • 181