Newbie - Directory/File Creation
pyth at devel.trillke.net
Tue Jul 8 22:39:35 CEST 2003
Peter Hansen wrote:
> 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,
Peter means os.makedirs() of course.
> 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.
Michael might be interested in the following "makepath" recipe:
More information about the Python-list