tags:

views:

29

answers:

1

I need to create a file with python, in the directory:

foo/bar/baz/filename.fil

The only problem, is that I don't know if baz, bar, or even foo have been created (they may have been, but the script doesn't guarantee it). So, obiously I can't do simply:

file = open('foo/bar/baz/filename.fil', 'wb')
# Stuff
# file.close()

because I will get an IOError if foo or bar or baz doesn't exist. So, I was thinking I could write a script that would

1.  Through a loop of os.path.split()s, get each directory.
2.  In a loop:  Test to see if each directory exists:
3.       If it doesn't: make it
4.  Then write the file.

However, it seems like python should have a better way of doing this, so am I missing something, or is the only (or best) way to do it is the algorithm I listed above?

Thank you.

+3  A: 

Use os.makedirs

unutbu
Ah, okay...I missed that one (was looking at os.makedir), anyway, it is possible though that the leaf directory would exist...although I guess that's an easy error to catch.
Leif Andersen
@Leif: Right. Catching the OSError exception is the easiest way.
unutbu