我正在编写一个 Python 脚本,我在其中将输出写入一个临时文件,然后在完成并关闭后将该文件移动到其最终目的地。脚本完成后,我希望输出文件具有与通过 open(filename,"w")
正常创建时相同的权限。实际上,该文件将具有 tempfile 模块用于临时文件的限制性权限集。
如果我就地创建输出文件,有没有办法让我弄清楚输出文件的“默认”文件权限是什么,以便我可以在移动临时文件之前将它们应用到临时文件?
最佳答案
作为记录,我遇到了类似的问题,这是我使用的代码:
import os
from tempfile import NamedTemporaryFile
def UmaskNamedTemporaryFile(*args, **kargs):
fdesc = NamedTemporaryFile(*args, **kargs)
# we need to set umask to get its current value. As noted
# by Florian Brucker (comment), this is a potential security
# issue, as it affects all the threads. Considering that it is
# less a problem to create a file with permissions 000 than 666,
# we use 666 as the umask temporary value.
umask = os.umask(0o666)
os.umask(umask)
os.chmod(fdesc.name, 0o666 & ~umask)
return fdesc
关于python - 如何获得 Python 中的默认文件权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7150826/