193

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.

martineau
  • 112,593
  • 23
  • 157
  • 280
Johan
  • 19,147
  • 28
  • 91
  • 110

3 Answers3

331

You need to expand the tilde manually:

my_dir = os.path.expanduser('~/some_dir')
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
  • 2
    So I didn't use os.path.expanduser, and did what the OP did, and python created "~" directory in my current directory. How can I delete that directory (without removing the actual home directory)? – Happy Mittal Aug 14 '19 at 11:14
  • 3
    @HappyMittal for others wondering, you can simply use `./` to reference your current directory, and thus `./~` to remove the folder `~` in the current directory. To be safer, it's easiest to simply provide the full path: `rm -rf path/to/bad/dir/~`. – alkasm Sep 17 '19 at 23:49
  • 1
    Or just escape it with a backslash: `rm \~` – DDMC Jun 19 '20 at 07:10
  • why though? matlab does this (and just about everything else) automatically. – 123 Sep 15 '21 at 20:56
  • Does it return string or Path object? – alper Dec 01 '21 at 18:53
82

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
  • 50,333
  • 7
  • 49
  • 57
  • 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
15

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

homedir = os.path.expanduser('~')
gruszczy
  • 39,180
  • 28
  • 124
  • 173