Python File Modification

File I/O Modification in Python.

Python - File Modification:

To modify a Python file programmatically, you typically read the file, make the necessary changes, and then write the modified content back to the file. Here's a basic example of how you can achieve this:

example.txt
txt (Text File) Copy Code
File modify concepts in Python.
main.py
PDF Copy Code
def modify_file(file_path, old_text, new_text):
    try:
        # Check if the file exists
        if not os.path.exists(file_path):
            print(f"File '{file_path}' not found.")
            return

        # Read the file
        with open(file_path, "r") as file:
            file_content = file.read()

        # Check if old_text exists in the file
        if old_text not in file_content:
            print(f"Text '{old_text}' not found in file '{file_path}'.")
            return

        # Perform the modification
        modified_content = file_content.replace(old_text, new_text)

        # Write the modified content back to the file
        with open(file_path, "w") as file:
            file.write(modified_content)

        print(f"File '{file_path}' modified successfully.")
    except Exception as e:
        print(f"An error occurred: {e}")


# Example usage
import os

file_path = "example.txt"
old_text = "File modify concepts in Python."
new_text = "The file has been modified successfully."
modify_file(file_path, old_text, new_text)
Output:
File 'example.txt' modified successfully.

Keep in mind that this is a basic example. Depending on your specific requirements, you might need to implement additional error handling or handle more complex file modifications.

Additionally, be cautious when modifying files programmatically, especially in production environments, to avoid unintended consequences. Always make sure to test thoroughly before applying such changes in critical systems.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.