Fabián Montero
Fabián Montero

Reputation: 1794

Whats the difference,speed and implementation, between os.mknod() and open('FILENAME', 'a') in python?

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?

Upvotes: 2

Views: 638

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

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

Upvotes: 4

Related Questions