How can I get the default file permissions in Python?

懵懂的女人 提交于 2019-12-10 03:59:41

问题


I am writing a Python script in which I write output to a temporary file and then move that file to its final destination once it is finished and closed. When the script finishes, I want the output file to have the same permissions as if it had been created normally through open(filename,"w"). As it is, the file will have the restrictive set of permissions used by the tempfile module for temp files.

Is there a way for me to figure out what the "default" file permissions for the output file would be if I created it in place, so that I can apply them to the temp file before moving it?


回答1:


For the record, I had a similar issue, here is the code I have used:

import os
from tempfile import NamedTemporaryFile

def UmaskNamedTemporaryFile(*args, **kargs):
    fdesc = NamedTemporaryFile(*args, **kargs)
    umask = os.umask(0)
    os.umask(umask)
    os.chmod(fdesc.name, 0o666 & ~umask)
    return fdesc



回答2:


There is a function umask in the os module. You cannot get the current umask per se, you have to set it and the function returns the previous setting.

The umask is inherited from the parent process. It describes, which bits are not to be set when creating a file or directory.



来源:https://stackoverflow.com/questions/7150826/how-can-i-get-the-default-file-permissions-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!