Ask Your Question
3

How can I prevent any changes to a file in the event of an exception while using Python fileinput?

asked 2022-11-26 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-12-16 10:00:00 +0000

devzero gravatar image

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().

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-26 11:00:00 +0000

Seen: 9 times

Last updated: Dec 16 '21