![]() |
Newbie - Directory/File Creation
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? |
Re: Newbie - Directory/File Creation
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: http://aspn.activestate.com/ASPN/Coo.../Recipe/117243 cheers, holger |
| All times are GMT. The time now is 08:26 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.