2

I want to create an empty file in python.

Currently I am using open('FILENAME', 'a').close() but I've seen a lot of people use os.mknod().

I did some research and it seems that os.mknod() uses tools from the OS you are using (hence its library name) and that open() is the "pythonic" way of creating an empty file.

What is the difference, in terms of speed and implementation between these two methods?

Would you recommend any other, more reliable or faster method to create an empty file?

Community
  • 1
  • 1
Fabián Montero
  • 1,613
  • 1
  • 16
  • 34
  • 1
    Your equivalence in semantics is wrong. I don’t know where you’ve seen mknod, but it is NOT for creating normal files. It’s for device files. So you are comparing apples to moonpies here. – deets Aug 13 '18 at 20:40

1 Answers1

4

you probably want to create regular files with mknod like this:

os.mknod(path, mode=0o600 | stat.S_IFREG)  # it seems that mode argument can be omitted for regular files

Well, don't since it's not portable (Unix only). Stick to open when you can (even if mknod is probably called behind the scenes on unix when creating a file, the performance difference is very small)

You can check another Q&A (Creating directory with mknod()) where the answer hints at the non-portability of os.mknod.

Another possible difference (didn't check that point) is that if the file already exists, mknod may return an error/exception, while open happily opens the file if the permissions allow it.

Don't forget that methods from os package are OS dependent. Using them sometimes ties you up with the system you're running on (even if it's safe to assume that os.remove and os.rename are available, with - of course - implementation differences).

Also note that open('FILENAME', 'a').close() does not necessarily create an empty file. If the file exists and the permissions are right, it just does nothing (a is for append).

  • To open with truncation and remain 100% portable, use open('FILENAME', 'w').close()
  • A slightly faster way is to open in binary without buffering: open('FILENAME', mode='wb', buffering=0).close()
  • For speed and reduced risks of non-portability: os.open is also an option since it's lower-level, and supported on all python environments that provide open: os.close(os.open('FILENAME',os.O_CREAT|os.O_BINARY))
Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Since the OP asked for "fast": It may be worth mentioning `open('FILENAME', mode='wb', buffering=0)` instead of `mode='w'`. For earlier 3.x (I can't remember if that means just 3.0, or 3.0-3.1), and for 2.x on systems with slow C stdio, `os.open` will be even faster (fast enough for optimized C programs like `dd`), still without any of the problems of abusing `mknod`. – abarnert Aug 13 '18 at 21:56
  • `os.open`, yes. I'll edit, blatantly copying your good comment. – Jean-François Fabre Aug 13 '18 at 21:57