user3307295
user3307295

Reputation: 31

How to write to a read-only file in Python

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.

Upvotes: 3

Views: 9939

Answers (2)

Maxime Lorant
Maxime Lorant

Reputation: 36161

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:

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

Upvotes: 7

Robᵩ
Robᵩ

Reputation: 168646

Try os.chmod() before opening the file.

Upvotes: 4

Related Questions