Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Creating directories

Tags:

python

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

import os
os.mkdir('~/Desktop/downloaded/')
like image 432
Bomb Avatar asked Mar 19 '10 22:03

Bomb


3 Answers

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"
like image 108
ghostdog74 Avatar answered Nov 15 '22 20:11

ghostdog74


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'
like image 29
tzot Avatar answered Nov 15 '22 18:11

tzot


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

like image 25
S.Lott Avatar answered Nov 15 '22 18:11

S.Lott