Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the try-except block to catch any exceptions that occur while using Python fileinput module, and use the os module's chmod() function to change the file permissions to read-only if an exception is caught. This will prevent any further changes to be made to the file.

Here's an example:

import fileinput
import os

filename = 'example.txt'

try:
    for line in fileinput.input(filename, inplace=True):
        # Your code here...

except Exception as e:
    # In case of an exception, change file permissions to read-only
    os.chmod(filename, 0o444)
    print("Exception caught: ", e)

finally:
    fileinput.close()

Here, we catch any exceptions that occur while iterating over the lines of the file using fileinput. If an exception is caught, we use the os.chmod() function to change the file permissions to read-only. We also print the exception message for debugging purposes.

Finally, we close the fileinput object using fileinput.close().