Last active
January 6, 2021 16:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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