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

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

问题描述

我试图创建一个只有用户可读和可写的文件( 0600 )。



是通过使用 os.open()这样做的唯一方法,如下所示:



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

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

解决方案

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

 与os.fdopen(os.open('/ path / to / file',os.O_WRONLY | os.O_CREAT,0o600), 'w')作为句柄:
handle.write(...)


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

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()

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?

解决方案

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天全站免登陆