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

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?

解决方案

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)

# 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值