Text Modifier - Python Programming Exercise

In this exercise, you will develop a Python program that reads a text file, replaces specified words, and saves the modified content into a new file. This exercise is perfect for practicing file handling, string manipulation, and command-line arguments in Python. By implementing this program, you will gain hands-on experience in handling file operations, string manipulation, and command-line arguments in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

Text Modifier

 Objective

Develop a Python program that reads a text file, replaces specified words, and saves the modified content into a new file.

The program should accept the filename, the target word, and the replacement word as command-line parameters:

Example command:
replace_text file.txt hello goodbye

The output will be saved in a file named "file.txt.out", where every instance of "hello" is replaced with "goodbye".

 Example Python Exercise

 Copy Python Code
import sys

def replace_text_in_file(file_name, target_word, replacement_word):
    """
    Reads a text file, replaces all occurrences of the target word with the replacement word,
    and saves the modified content into a new file named 'file_name.out'.
    
    Parameters:
    file_name (str): The name of the input file to read.
    target_word (str): The word to be replaced.
    replacement_word (str): The word to replace the target word with.
    """
    try:
        # Open the input file in read mode
        with open(file_name, 'r') as file:
            # Read all the lines from the file
            content = file.read()
        
        # Replace all occurrences of target_word with replacement_word
        modified_content = content.replace(target_word, replacement_word)
        
        # Create the output file name by appending '.out' to the original file name
        output_file_name = file_name + '.out'
        
        # Open the output file in write mode and save the modified content
        with open(output_file_name, 'w') as output_file:
            output_file.write(modified_content)
        
        print(f"Modification successful! The modified content has been saved to '{output_file_name}'")
    
    except FileNotFoundError:
        print(f"The file '{file_name}' was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")


# Main program execution
if __name__ == "__main__":
    # Check if the correct number of arguments are provided
    if len(sys.argv) != 4:
        print("Usage: replace_text   ")
    else:
        # Extract command-line arguments
        file_name = sys.argv[1]
        target_word = sys.argv[2]
        replacement_word = sys.argv[3]
        
        # Call the replace_text_in_file function
        replace_text_in_file(file_name, target_word, replacement_word)

 Output

Assume file.txt contains the following text:
hello world
hello there
hello again

If you run the following command:
python replace_text.py file.txt hello goodbye

The program will create a new file, file.txt.out, with the following content:
goodbye world
goodbye there
goodbye again

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Count characters in a text file

    In this exercise, you will develop a Python program that counts how many times a specific character appears in a given file (of any type). This exercise is per...

  •  Binary File Reading (BMP Example)

    In this exercise, you will develop a Python program that verifies if a BMP image file is valid by checking its header. This exercise is perfect for practicing ...

  •  Saving Data to a Binary File

    In this exercise, you will develop a Python program that prompts the user to enter their name, age (as a byte), and birth year (as an integer), then saves this inform...

  •  Reverse the contents of a text file

    In this exercise, you will develop a Python program that inverts the contents of a text file. This exercise is perfect for practicing file handling, loops, and...

  •  Working with binary GIF files

    In this exercise, you will develop a Python program to validate the structure of a GIF image file. This exercise is perfect for practicing file handling, byte ...

  •  Database of Contacts using File Storage

    In this exercise, you will develop a Python program that extends the "contacts database" by implementing functionality to load data from a file at the start of each s...