Count characters in a text file - Python Programming Exercise

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 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

Count Characters In A Text File

 Objective

Develop a Python program that counts how many times a specific character appears in a given file (of any type).

The program should allow the user to input the file name and the character to search for, or these can be passed as command-line arguments:

Example:
count example.txt a

The program should display the count of occurrences of the specified character.

(Feel free to design the user interaction and display appropriate guidance if needed.)

 Example Python Exercise

 Copy Python Code
import sys

def count_character_in_file(file_name, character):
    """
    Counts how many times a specific character appears in a given file.
    
    Parameters:
    file_name (str): The name of the file to search.
    character (str): The character to search for in the file.
    
    Returns:
    int: The count of occurrences of the specified character.
    """
    count = 0
    try:
        # Open the file in read mode
        with open(file_name, 'r') as file:
            # Read the content of the file
            content = file.read()
            
            # Count the occurrences of the specified character
            count = content.count(character)
        
        return count
        
    except FileNotFoundError:
        print(f"The file '{file_name}' was not found.")
        return -1  # Indicates file was not found
    except Exception as e:
        print(f"An error occurred: {e}")
        return -1  # Indicates an unexpected error

# Main program execution
if __name__ == "__main__":
    # Check if the correct number of arguments are provided
    if len(sys.argv) == 3:
        # Extract command-line arguments
        file_name = sys.argv[1]
        character = sys.argv[2]
        
        # Validate that only one character is provided
        if len(character) != 1:
            print("Please provide exactly one character to search for.")
        else:
            # Call the function to count the character in the file
            count = count_character_in_file(file_name, character)
            if count != -1:
                print(f"The character '{character}' appears {count} times in the file '{file_name}'.")
    else:
        # Ask the user for the file name and character if no command-line args
        file_name = input("Please enter the file name: ")
        character = input("Please enter the character to search for: ")
        
        # Validate that only one character is provided
        if len(character) != 1:
            print("Please provide exactly one character to search for.")
        else:
            # Call the function to count the character in the file
            count = count_character_in_file(file_name, character)
            if count != -1:
                print(f"The character '{character}' appears {count} times in the file '{file_name}'.")

 Output

Assume example.txt contains:
apple
banana
avocado

If you run the following command:
python count_character.py example.txt a

The program will output:
The character 'a' appears 6 times in the file 'example.txt'.

If the file does not exist or an error occurs, the program will display:
The file 'nonexistent.txt' was not found.

 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.

  •  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...

  •  Transform a Text File to Uppercase

    In this exercise, you will develop a Python program that reads the contents of a text file and writes it to a new file, converting all lowercase letters to uppercase....