python - 如何获得 Python 中的默认文件权限?

标签 python file-permissions temporary-files

我正在编写一个 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/

相关文章:

python - 什么更快?列表的最小值然后是最小值的索引,vs 遍历列表

apache-spark - hadoop.dll,winutils.exe和在hadoop上构建的多个应用程序

file-permissions - 通过Unix终端更改多个文件的文件权限

python - 将数据库查询转换为有用的格式

python - 为什么 `optimizer.minimize()` 不返回损失 `tf.slim.learning.train()` ?

flutter - 当 “flutter upgrade”时,出现 “Permission denied”错误

python - 临时文件目录最终是否被系统清除

c - 为什么我不能 "freopen"和 "tmpfile"?

Windows 目录永远不会包含临时文件的非 ASCII 字符?

python - 分水岭分割后提取对象