Newbie - Directory/File Creation

Gerhard Häring gh at ghaering.de
Tue Jul 8 22:40:56 CEST 2003


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')

If you want to have a backslash in a string, you have to double it, 
because the backslash is an escape character in Python strings. So this 
would be:

TestFile = open("TestDir\\TestTest.out", 'w')

Alternatively, you can use a raw string:

TestFile = open(r"TestDir\TestTest.out", 'w')

or just use a forward slash, which works fine on Windows as well:

TestFile = open(r"TestDir/TestTest.out", 'w')

or, to be politically correct, you can use:

import os
TestFile = open(os.path.join("TestDir", TestTest.out"), 'w')

> Shouldn't open be smart enough to create the TestDir directory before
> creating TestTest.out   ?

No, explicit is better than implicit. [1]

> Is there another command that will do this?

Sure, os.mkdir.

-- Gerhard

[1] Try "import this" at an interactive Python prompt for this and more 
Python Zen :-)





More information about the Python-list mailing list