Python Code Examples

Growing collection of Python programming examples

def compare_files_with_dictionary(file1_path, file2_path, key_column_index=0):
    """
    Compares two files and finds corresponding rows based on a specified key column.

    Args:
        file1_path: Path to the first file.
        file2_path: Path to the second file.
        key_column_index: Index of the column to use as the key for comparison.

    Returns:
        A list of tuples, where each tuple contains a corresponding row from the first and second files.
    """

    key_column_index = int(key_column_index)

    # Read the contents of both files into lists of lines
    with open(file1_path, "r") as f1, open(file2_path, "r") as f2:
        lines1 = f1.readlines()
        lines2 = f2.readlines()

    # Create a dictionary to store rows from the first file, indexed by the key column
    key_to_row1 = {}
    for line1 in lines1:
        row1 = line1.strip().split()
        key = row1[key_column_index]
        key_to_row1[key] = row1

    # Find corresponding rows in the second file based on the key
    corresponding_rows = []
    for line2 in lines2:
        row2 = line2.strip().split()
        key = row2[key_column_index]
        if key in key_to_row1:
            corresponding_rows.append((key_to_row1[key], row2))

    return corresponding_rows

# Example usage
file1_path = "file1.txt"
file2_path = "file2.txt"
key_column_index = 0  # Assuming the key is in the first column

corresponding_rows = compare_files_with_dictionary(file1_path, file2_path, key_column_index)

for row1, row2 in corresponding_rows:
    print("Corresponding rows:")
    print(row1)
    print(row2)

+