Newbie - Directory/File Creation

  • Thread starter Michael J Whitmore
  • Start date
M

Michael J Whitmore

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?
 
H

holger krekel

Peter said:
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/Cookbook/Python/Recipe/117243

cheers,

holger
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top