如何获取Python中的默认文件权限?
我正在编写一个 Python 脚本,其中我将输出写入临时文件,然后在完成并关闭后将该文件移动到其最终目的地。脚本完成后,我希望输出文件具有与通过 open(filename,"w") 正常创建的权限相同的权限。事实上,该文件将具有临时文件模块对临时文件使用的限制性权限集。
有没有办法让我弄清楚如果我就地创建输出文件,它的“默认”文件权限是什么,以便我可以在移动临时文件之前将它们应用到临时文件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
作为记录,我遇到了类似的问题,这是我使用的代码:
For the record, I had a similar issue, here is the code I have used:
os< 中有一个函数
umask
/code> 模块。您无法获取当前的 umask 本身,您必须设置它并且该函数返回之前的设置。umask 是从父进程继承的。它描述了创建文件或目录时不要设置的位。
There is a function
umask
in theos
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.
这种方式虽然缓慢但安全,并且适用于任何具有“umask”shell 命令的系统:
This way is slow but safe and will work on any system that has a 'umask' shell command:
这个函数在一些python包中实现,例如 点 和 安装工具。
This function is implemented in some python packages, e.g. pip and setuptools.