开发者

Python: Creating directories

I want to create a direc开发者_如何学Pythontory (named 'downloaded') on in my desktop directory; isn't this working?:

import os
os.mkdir('~/Desktop/downloaded/')


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


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'


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜