I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:
import os
os.mkdir('~/Desktop/downloaded/')
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"
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'
You can't simply use ~
You must use os.path.expanduser to replace the ~
with a proper path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With