344

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?

6
  • @LevLevitsky because I'd have to close it again :P. I have to create thousands of files, and just touching the file seems cleaner. Commented Sep 29, 2012 at 17:26
  • 1
    FYI, while using an external command for this is always bad, the proper way to execute it would be subprocess.call(['touch', x]) Commented Sep 29, 2012 at 17:31
  • 5
    @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. Commented Sep 29, 2012 at 17:33
  • @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. Commented Sep 29, 2012 at 18:04
  • 7
    How do you think touch does its job? git.savannah.gnu.org/cgit/coreutils.git/tree/src/… line 134 Commented Aug 2, 2015 at 16:22

2 Answers 2

591

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)
Sign up to request clarification or add additional context in comments.

9 Comments

Yes, opening a file with the w (write) flag empties it while opening it with a (append) doesn't.
Refcounting closing the file immediate is not to be relied on. This is not a matter of cleanliness, as refcounting is just an implementation detail. No Python except CPython does it. Want to make your program five times faster with PyPy, or run it in a Java/.NET environment with Jython/IronPython? Well too bad you didn't close those files, now your program is leaking like a sieve ;) It's especially awful since 2.5, as with makes it easier to close the file timely (and even in the face of exceptions and circular references) and the code becomes clearer to boot.
@ThiefMaster Wouldn't it be better not to talk about specific behavior of CPython in all cases where the question doesn't mention this concrete implementation? :)
A better one-liner is probably with open(filename, mode='a'): pass
In Python 3.3 the 'x' mode was added: "open for exclusive creation, failing if the file already exists" docs.python.org/3/library/functions.html#open
|
65

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.

4 Comments

Great point. See also docs.python.org/3/library/os.html
it's also unix-only. Won't work on windows
It is the only way if you absolutely want to avoid opening the file, even though it's primary use-case is to create device files and things like that, which is probably the reason why it requires root privileges on some systems. For compatibility reasons I would always stick to the open().close() approach wherever possible.
@CharlieParker Because opening for writing is the way to create a file right down to the operating system's API. pathlib and the path-like objects are a fairly recent addition to Python and absolutely superfluous in my opinion (like most features introduced after 3.6), but yes, that will work. However, if you look at the source code, you will find that it also just calls os.open() followed by os.close() to do the deed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.