pythonpython-2.7file-iocreate-directory

Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist


I'm trying to create and write to a text file using Python, like so:

afile = 'D:\\temp\\test.txt'
outFile = open(afile, 'w' )
outFile.write('Test.')
outFile.close()

But I get an error like:

Error: 2
Traceback (most recent call last):
  File "<maya console>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'D:\\temp\\test.txt'

When I tried to look for a solution, most answers I found related to the slashes in the path. But I still got errors if I tried using 'D:/temp/test.txt', or r'D:\temp\test.txt' as the path.

I can, however, create a file at the root of the drive: the filenames 'D:/test.txt', 'D:\\test.txt' and r'D:\test.txt' all work.

It seems that I can't create the directory path I would like while trying to create the file.

How should I create a file at a specific path in Python? Does open() create directories if they don't exist, or do I need to explicitly create the directory path first?


Solution

  • You are correct in surmising that the parent directory for the file must exist in order for open to succeed. The simple way to deal with this is to make a call to os.makedirs.

    From the documentation:

    os.makedirs(path[, mode])

    Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.

    So your code might run something like this:

    filename = ...
    dirname = os.path.dirname(filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    with open(filename, 'w'):
        ...