Merging and Sorting Files - Python Programming Exercise

In this exercise, you will develop a Python program that merges the contents of multiple text files into a single file and sorts the content alphabetically or numerically, depending on the file type. This exercise is perfect for practicing file handling, data sorting, and error handling in Python. By implementing this program, you will gain hands-on experience in handling file operations, data sorting, and error handling 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

Memory Management Techniques

 Exercise

Merging And Sorting Files

 Objective

Develop a Python program that merges the contents of multiple text files into a single file and sorts the content alphabetically or numerically, depending on the file type. The program should read from several input files, combine their contents, and write the sorted result to a new file. Ensure that the program handles different file types appropriately and includes error handling for file not found or permission issues.

 Example Python Exercise

 Copy Python Code
import os

def sort_content(file_contents, is_numeric=False):
    """Sorts the content of the file. If the content is numeric, it sorts numerically; else, alphabetically."""
    try:
        if is_numeric:
            # Sort numerically by converting content to integers
            file_contents.sort(key=lambda x: float(x.strip()))
        else:
            # Sort alphabetically
            file_contents.sort()
    except ValueError:
        print("Error: Could not sort numerically. Ensure all lines are numeric.")
        raise
    return file_contents

def read_file(file_name):
    """Reads the content of a file and returns it as a list of lines."""
    try:
        with open(file_name, 'r') as file:
            content = file.readlines()
        return content
    except FileNotFoundError:
        print(f"Error: The file '{file_name}' was not found.")
        raise
    except PermissionError:
        print(f"Error: Permission denied to read the file '{file_name}'.")
        raise

def merge_and_sort(files, output_file, is_numeric=False):
    """Merges the content of multiple files, sorts it, and writes the result to an output file."""
    all_contents = []
    
    # Read contents from all input files
    for file in files:
        try:
            content = read_file(file)
            all_contents.extend(content)
        except (FileNotFoundError, PermissionError):
            continue  # Skip files that couldn't be read

    # Sort the content
    sorted_content = sort_content(all_contents, is_numeric)
    
    # Write the sorted content to the output file
    try:
        with open(output_file, 'w') as out_file:
            out_file.writelines(sorted_content)
        print(f"Successfully written the sorted content to '{output_file}'.")
    except PermissionError:
        print(f"Error: Permission denied to write to the file '{output_file}'.")
        raise

def main():
    """Main function to handle input and output files, and sorting type (numeric or alphabetical)."""
    # Input: List of files to be merged and sorted
    files = input("Enter the file names to merge (comma separated): ").split(',')
    files = [file.strip() for file in files]  # Clean up the file names

    # Output: Name of the output file
    output_file = input("Enter the name of the output file: ").strip()

    # Determine whether the content should be sorted numerically or alphabetically
    file_type = input("Should the content be sorted numerically (yes/no)? ").strip().lower()
    is_numeric = file_type == 'yes'

    try:
        merge_and_sort(files, output_file, is_numeric)
    except Exception as e:
        print(f"An error occurred: {e}")

# Run the program
if __name__ == "__main__":
    main()

 Output

Enter the file names to merge (comma separated): file1.txt, file2.txt, file3.txt
Enter the name of the output file: merged_sorted.txt
Should the content be sorted numerically (yes/no)? yes
Successfully written the sorted content to 'merged_sorted.txt'.

Enter the file names to merge (comma separated): file1.txt, file2.txt, file3.txt
Enter the name of the output file: merged_sorted.txt
Should the content be sorted numerically (yes/no)? no
Successfully written the sorted content to 'merged_sorted.txt'.

 Share this Python Exercise

 More Python Programming Exercises of Memory Management Techniques

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.

  •  ArrayList: Storing Points

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to store a collection of points, where each point is represented by...

  •  File Search Operations

    In this exercise, you will develop a Python program that searches for a specific word or phrase within a text file. This exercise is perfect for practicing fil...

  •  Implementing a Queue Using List

    In this exercise, you will develop a Python program to implement a queue using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Building a Stack Using Lists

    In this exercise, you will develop a Python program to implement a stack using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Working with Queue Collections

    In this exercise, you will develop a Python program to demonstrate the use of queue collections. This exercise is perfect for practicing data structures, queue...

  •  Queue and Stack for Reverse Polish Notation

    In this exercise, you will develop a Python program to evaluate expressions written in Reverse Polish Notation (RPN) using a queue and stack. This exercise is ...