Write file with specific permissions in Python

前端 未结 6 1224
一个人的身影
一个人的身影 2020-12-01 15:37

I\'m trying to create a file that is only user-readable and -writable (0600).

Is the only way to do so by using os.open() as follows?

6条回答
  •  我在风中等你
    2020-12-01 16:09

    I'd do differently.

    from contextlib import contextmanager
    
    @contextmanager
    def umask_helper(desired_umask):
        """ A little helper to safely set and restore umask(2). """
        try:
            prev_umask = os.umask(desired_umask)
            yield
        finally:
            os.umask(prev_umask)
    
    # ---------------------------------- […] ---------------------------------- #
    
            […]
    
            with umask_helper(0o077):
                os.mkdir(os.path.dirname(MY_FILE))
                with open(MY_FILE, 'wt') as f:
                    […]
    
    

    File-manipulating code tends to be already try-except-heavy; making it even worse with os.umask's finally isn't going to bring your eyes any more joy. Meanwhile, rolling your own context manager is that easy, and results in somewhat neater indentation nesting.

提交回复
热议问题