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.

Leif Andersen
  • 21,580
  • 20
  • 67
  • 100

1 Answers1

4

Use os.makedirs

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 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 Jul 23 '10 at 20:42
  • @Leif: Right. Catching the OSError exception is the easiest way. – unutbu Jul 23 '10 at 21:08