11

I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:

import os os.mkdir('~/Desktop/downloaded/') 
2
  • If the Desktop dir is in other language????? how to locate on Desktop in any language? Commented Jan 30, 2011 at 18:45
  • For code that does the equivalent of "mkdir -p" see stackoverflow.com/q/600268/319741 Commented Mar 29, 2012 at 14:16

3 Answers 3

15

You can't simply use ~ You must use os.path.expanduser to replace the ~ with a proper path.

Sign up to request clarification or add additional context in comments.

2 Comments

So you could replace that code with os.mkdir(os.expanduser('~/Desktop/Downloaded/')).
@Leafstorm os.path.expanduser, not os.expanduser.
10

Use

import os os.mkdir(os.path.expanduser("~/Desktop/downloaded")) 

The ~ character is a POSIX shell convention that represents the contents of the HOME environment variable. So, when you type in a shell:

$ mkdir ~/Desktop/downloaded 

it's the same as typing

$ mkdir $HOME/Desktop/downloaded 

Try changing the HOME environment variable to verify what I say.

Since it's a shell convention, it's something that neither the kernel treats specially, nor Python, and the python os.mkdir function is just a wrapper around the kernel mkdir(2) system call. As a conveniency, Python provides the os.path.expanduser function to replace the tilde with the contents of the HOME env var.

$ HOME=/tmp # it is already exported $ python Python 2.6.4 (r264:75706, Mar 2 2010, 00:28:19) [GCC 4.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.expanduser("~/dada") '/tmp/dada' 

Comments

2

another way, use os.environ

import os home=os.environ["HOME"] path=os.path.join(home,"Desktop","download") try: os.mkdir(path) except IOError,e: print e else: print "Successful" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.