简体   繁体   中英

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM