如何用Python写入只读文件

时间:2022-09-11 16:48:38

Is there a way to write to a read-only file in Python? I am trying to write a script which helps me add debug statements at the start of every function in a given file. But the issue I have is that before I run the script, I have to manually remove the read-only flag on the file. is there anyway I can write to read-only files without manually having to remove them? Any suggestions will be deeply appreciated. Thanks.

有没有办法在Python中写入只读文件?我正在尝试编写一个脚本,它可以帮助我在给定文件中的每个函数的开头添加调试语句。但我遇到的问题是,在运行脚本之前,我必须手动删除文件上的只读标志。无论如何我可以写入只读文件而无需手动删除它们?任何建议都将深表感谢。谢谢。

2 个解决方案

#1


4  

Try os.chmod() before opening the file.

在打开文件之前尝试os.chmod()。

#2


4  

If the user that runs the script doesn't have permissions to write in a file, you can't edit it. Basically, you need to have the w permission to edit a file. See Linux file permissions for more information.
If you want to get rid of it, you should make the file writable directly, or try to change its chmod with the os module, if you have enough permission to do this:

如果运行脚本的用户没有写入文件的权限,则无法对其进行编辑。基本上,您需要具有w权限才能编辑文件。有关更多信息,请参阅Linux文件权限。如果你想摆脱它,你应该直接使文件可写,或者尝试用os模块更改它的chmod,如果你有足够的权限这样做:

>>> os.chmod('path_to/file', 0755)

#1


4  

Try os.chmod() before opening the file.

在打开文件之前尝试os.chmod()。

#2


4  

If the user that runs the script doesn't have permissions to write in a file, you can't edit it. Basically, you need to have the w permission to edit a file. See Linux file permissions for more information.
If you want to get rid of it, you should make the file writable directly, or try to change its chmod with the os module, if you have enough permission to do this:

如果运行脚本的用户没有写入文件的权限,则无法对其进行编辑。基本上,您需要具有w权限才能编辑文件。有关更多信息,请参阅Linux文件权限。如果你想摆脱它,你应该直接使文件可写,或者尝试用os模块更改它的chmod,如果你有足够的权限这样做:

>>> os.chmod('path_to/file', 0755)