在 Python 中写入具有特定权限的文件 [英] Write file with specific permissions in Python

查看:26
本文介绍了在 Python 中写入具有特定权限的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个只有用户可读和可写的文件 (0600).

I'm trying to create a file that is only user-readable and -writable (0600).

使用 os.open() 是否是唯一的方法,如下所示?

Is the only way to do so by using os.open() as follows?

import os
fd = os.open('/path/to/file', os.O_WRONLY, 0o600)
myFileObject = os.fdopen(fd)
myFileObject.write(...)
myFileObject.close()

理想情况下,我希望能够使用 with 关键字,以便我可以自动关闭对象.有没有更好的方法来做我在上面做的事情?

Ideally, I'd like to be able to use the with keyword so I can close the object automatically. Is there a better way to do what I'm doing above?

推荐答案

有什么问题?file.close() 将关闭文件,即使它是用 os.open() 打开的.

What's the problem? file.close() will close the file even though it was open with os.open().

with os.fdopen(os.open('/path/to/file', os.O_WRONLY | os.O_CREAT, 0o600), 'w') as handle:
  handle.write(...)

这篇关于在 Python 中写入具有特定权限的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆