yy

It sounds like you want a Python script that will:
 * Search for files in the current directory (or a specified directory) whose names contain the substring "abcd".
 * Open each matching file.
 * Read the content of the file.
 * Replace all occurrences of the string "qwerty" with "youo" within the content.
 * Write the modified content back to the file.
Here is a Python script to accomplish this. It uses the os module for file system operations and the re module for robust string replacement, although a simple str.replace() is also fine for this specific case. I will use str.replace() for simplicity.
Python Code
import os

def replace_text_in_files(directory='.', filename_substring='abcd', old_text='qwerty', new_text='youo'):
    """
    Searches for files containing a specific substring in their name within a directory,
    and replaces a given text string inside those files.

    Args:
        directory (str): The directory to search in. Defaults to the current directory ('.').
        filename_substring (str): The substring to look for in the file names.
        old_text (str): The text to be replaced.
        new_text (str): The replacement text.
    """
    print(f"Starting search in directory: {os.path.abspath(directory)}")
    found_files = 0
    modified_files = 0

    try:
        # 1. Iterate over all entries in the directory
        for filename in os.listdir(directory):
            filepath = os.path.join(directory, filename)

            # Check if it's a file and contains the filename substring
            if os.path.isfile(filepath) and filename_substring in filename:
                print(f"\n--- Processing file: {filename} ---")
                found_files += 1

                try:
                    # 2. Open and read the entire content
                    with open(filepath, 'r') as file:
                        original_content = file.read()

                    # 3. Check if the text to be replaced exists
                    if old_text in original_content:
                        print(f"Found '{old_text}' inside the file. Replacing...")

                        # 4. Replace the text
                        new_content = original_content.replace(old_text, new_text)

                        # 5. Open the file again in write mode ('w') and write the new content
                        with open(filepath, 'w') as file:
                            file.write(new_content)

                        modified_files += 1
                        print(f"Replacement successful. File updated.")
                    else:
                        print(f"'{old_text}' not found in file. Skipping update.")

                except Exception as e:
                    print(f"An error occurred while reading/writing file {filename}: {e}")

    except FileNotFoundError:
        print(f"Error: Directory not found: {directory}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

    print("\n--- Summary ---")
    print(f"Files matching '{filename_substring}': {found_files}")
    print(f"Files successfully modified: {modified_files}")
    print("Operation complete.")

# --- Execution ---
if __name__ == "__main__":
    # You can change '.' to a specific path like '/home/user/my_docs'
    # The default '.' means the current working directory where the script is run.
    replace_text_in_files(
        directory='.',
        filename_substring='abcd',
        old_text='qwerty',
        new_text='youo'
    )

How to Use the Code
 * Save: Save the code above as a Python file (e.g., file_replacer.py).
 * Create Test Files: In the same directory where you saved the script, create a few test files.
   * test_abcd_1.txt (content: This is a test with qwerty data.)
   * another_abcd_file.log (content: The key is qwerty but also another qwerty.)
   * not_matching_file.txt (content: This should be ignored.)
 * Run: Open your terminal or command prompt, navigate to that directory, and run the script:
   python file_replacer.py

 * Check: After execution, open the files that contained "abcd" in their name. The text "qwerty" should now be replaced with "youo".

Reactions

Post a Comment

0 Comments