tags:

views:

293

answers:

3

Hi

I have a little problem with ~ in my paths.

This code example creates some dirs called "~/some_dir", and do not understand that I wanted to create some_dir in my home dir.

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

Note this is on a linux based system.

Thanks Johan


Solution:

Thanks all, if I added the line SilentGhost and ddaa suggested it works as you would expect it to.

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

you need to expand the tilde manually:

my_dir = os.path.expanduser('~/some_dir')
SilentGhost
Thanks___________ .
Johan
+4  A: 

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

homedir = os.path.expanduser('~')
gruszczy
+6  A: 

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
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
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