Skip to content

Instantly share code, notes, and snippets.

@gunchev
Last active January 6, 2021 16:13
Show Gist options
  • Save gunchev/13a207f7de37fc2cc94c933e929f7881 to your computer and use it in GitHub Desktop.
Save gunchev/13a207f7de37fc2cc94c933e929f7881 to your computer and use it in GitHub Desktop.
Exclusively create a new binary file in python 2, like 'x' mode in python 3
#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
>>> f1 = create_file('/tmp/test.bin')
>>> f2 = create_file('/tmp/test.bin')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in create_file
OSError: [Errno 17] File exists: '/tmp/test.bin'
>>> f1.close()
>>> os.unlink('/tmp/test.bin')
"""
import os
def create_file(file_path):
"""Create a new file, like the 'x' file mode in python 3
See https://alexwlchan.net/2016/03/exclusive-create-python/ for how to use
"""
fd = os.open(file_path, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o644)
return os.fdopen(fd, 'wb')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment