294
votes

I'd like to create a file with path x using python. I've been using os.system(y) where y = 'touch %s' % (x). I've looked for a non-directory version of os.mkdir, but I haven't been able to find anything. Is there a tool like this to create a file without opening it, or using system or popen/subprocess?

2
@LevLevitsky because I'd have to close it again :P. I have to create thousands of files, and just touching the file seems cleaner. - tkbx
FYI, while using an external command for this is always bad, the proper way to execute it would be subprocess.call(['touch', x]) - ThiefMaster
@tkbx: "clean" can mean many things to many people. For example, spawning a completely separate process thousands of times is not very clean in my opinion. Sure, on modern OS's running on modern hardware a new process can be spawned pretty quickly, but it's still a crazy amount of overhead for such a small thing. - Bryan Oakley
@BryanOakley to describe emotions the best way I can, "clean" to me is the program being "truly finished", with no possibility for error. print(x); os.mkdir(y), zint = int(z) would be a very "clean" program in my opinion, because it's all functions that preform their task with no room for error or overhead. Something like os.touch() would seem "clean" to me, because however many thousands of times it runs, the workflow is the same, and it even if the script takes a year, I know the code has fulfilled it's purpose without any error margin by the end. - tkbx
How do you think touch does its job? git.savannah.gnu.org/cgit/coreutils.git/tree/src/… line 134 - msw

2 Answers

517
votes

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)
54
votes

Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt"). The only drawback is that this call requires root privileges on OSX.