在Python中将文件更改为只读模式 [英] Change file to read-only mode in Python

查看:1101
本文介绍了在Python中将文件更改为只读模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个数据处理代码,在其中创建一个新文件,把处理过的数据写入这个文件并关闭。但是文件必须以只读模式关闭,以免意外修改。这可以在Python中完成吗?

解决方案

为此,您可以使用 os.chmod

  import stat 
from stat import S_IREAD,S_IRGRP,S_IROTH

filename =path / to / file
os。 chmod(filename,S_IREAD | S_IRGRP | S_IROTH)

请注意,假设您拥有适当的权限,您不仅需要所有者能够读取文件。如果不是这样,请删除 S_IROTH S_IRGRP



如果您需要使文件再次可写,只需调用 os.chmod c $ c>如此:

  from stat import S_IWUSR#需要将这个导入添加到
$上面b $ b os.chmod(文件名,S_IWUSR | S_IREAD)#这使文件读/写为所有者



在打开文件进行写入之前,只需调用它,然后调用第一个表单,在完成后再次将其设置为只读。


I am writing a data processing code, in which I create a new file, write processed data in to this file and close. But the file has to be closed in read-only mode, so that it would not be accidentally modified. Can this be done in Python?

解决方案

For this you use os.chmod

import os
from stat import S_IREAD, S_IRGRP, S_IROTH

filename = "path/to/file"
os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)

Note that this assumes you have appropriate permissions, and that you want more than just the owner to be able to read the file. Remove S_IROTH and S_IRGRP as appropriate if that's not the case.

UPDATE

If you need to make the file writable again, simply call os.chmod as so:

from stat import S_IWUSR # Need to add this import to the ones above

os.chmod(filename, S_IWUSR|S_IREAD) # This makes the file read/write for the owner

Simply call this before you open the file for writing, then call the first form to make it read-only again after you're done.

这篇关于在Python中将文件更改为只读模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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