Feed on
Posts
Comments

assuming you’re running some *nix (including mac os x), here’s how to create a directory from within a python script. note that we need to check if the directory exists before creating a directory (if you try and overwrite a directory, python will throw an error).

here goes:

import os;

dirname = “my_dir_name”
if not os.path.isdir(“./” + dirname + “/”):
os.mkdir(“./” + dirname + “/”)

note that the last line needs to be indented (silly blogger won’t let me indent that line!)


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

14 Responses to “create a directory in python”

  1. on 24 Mar 2008 at 12:08 am Chris Nicholls

    Hey, I randomly found this page on google the other day when I was working on some python stuff. This post helped. Thanks.

    But what i actually wanted to comment on was the header at the top of your theme. I think it’s fantastic. Way to go.

    Cheers

  2. on 24 Mar 2008 at 7:27 am Lawrence David

    it’s what happens when you’ve got too much time on your hands during 1st year of grad school :)

  3. on 11 Jun 2008 at 12:22 pm Slava

    Super!!!

  4. [...] needed to learn how to create directories using Python and found this great resource (digression: check out this author’s page headers – way [...]

  5. on 15 May 2009 at 11:13 am Eric Wendelin

    Thanks a bunch, this is exactly what I was looking for. :)

  6. on 30 Jul 2009 at 8:02 pm Aman Aggarwal

    Thanks!

  7. on 02 Sep 2009 at 8:22 am NT

    Nearly 18 months on I have to echo the first commenter’s thoughts – totally cool header.

  8. on 13 Sep 2009 at 11:00 pm Matthew

    This also works on Windows unchanged, but like it better like this:

    [code]
    dirname = "my_dir_name"
    if not os.path.isdir(os.path.join(os.getcwd(), dirname)):
    os.mkdir(os.path.join(os.getcwd(), dirname))
    [/code]

    My $0.02. Nice site BTW.

  9. on 17 Jan 2010 at 12:51 pm Graham

    Thanks exactly what I was looking for. Modified Matthew’s code slightly to incorporate recursive directory creation.

    #code
    import os;

    dirname = “mydir”
    if not os.path.isdir(os.path.join(os.getcwd(), dirname)):
    os.makedirs(os.path.join(os.getcwd(), dirname))
    print os.getcwd()

  10. on 22 Jan 2010 at 6:00 am nikunj

    Hey, Many thnx for this useful post..!!

  11. on 28 Jul 2011 at 10:01 am Saurabh

    this is simply.
    exactly what i was looking for.

  12. on 28 Jul 2011 at 10:03 am Saurabh

    can you guide me how to create a Remote Directory ?

  13. on 22 Sep 2011 at 2:54 pm Shruti

    Cool Story Bro! super cool banner!

  14. on 11 Aug 2012 at 5:41 am Sanket

    Thanks a lot it helped me.

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.