Newbie - Directory/File Creation

Peter Hansen peter at
Tue Jul 8 22:18:44 CEST 2003

Michael J Whitmore wrote:
> If I do the following, a file is created in the current working
> directory:
>     TestFile = open("TestTest.out", 'w')
> My question is how to create a file that includes a pathname without
> having to mkdir beforehand.
>     Example:
>     TestFile = open("TestDir\TestTest.out", 'w')
> Shouldn't open be smart enough to create the TestDir directory before
> creating TestTest.out   ?
> Is there another command that will do this?

Use os.path.makedirs() first, although if you really want to do this,
I would separate the "ensure this directory exists" part from the 
"create this file" part.  Or combine the two, but call your own method
which internally checks whether the path exists (os.path.split() and
os.path.isdir() are good for part of this), then creates it if necessary
using makedirs(), then finally creates the file and returns the
file object.


More information about the Python-list mailing list