import csv
from typing import List, Optional
def merge_deduplicate_csvs(
input_files: List[str],
output_file: str,
dedup_columns: Optional[List[str]] = None,
encoding: str = 'utf-8'
) -> None:
"""
Merges multiple large CSV files into a single output CSV file, removing duplicates
based on specified columns or exact row matches. Processes files in a streaming
fashion to handle large files efficiently, preserving the order of first occurrence.
- Assumes all CSV files have headers and the same column structure.
- Uses the header from the first file.
- If `dedup_columns` is None (default), deduplicates on exact full row matches.
- If `dedup_columns` is provided (e.g., ['id', 'name']), deduplicates based on those columns only.
- Memory usage depends on the number of unique keys/rows (stores hashable tuples of strings).
Example usage:
merge_deduplicate_csvs(
input_files=['file1.csv', 'file2.csv'],
output_file='merged_unique.csv',
dedup_columns=['user_id'] # Optional: dedup on specific columns
)
:param input_files: List of paths to input CSV files.
:param output_file: Path to the output CSV file.
:param dedup_columns: Optional list of column names for deduplication key.
:param encoding: File encoding (default: 'utf-8').
:raises ValueError: If dedup_columns contain names not in the first file's header.
"""
if not input_files:
return
seen = set()
first_file = True
header = None
col_indices: Optional[List[int]] = None
with open(output_file, 'w', newline='', encoding=encoding) as out_f:
writer = csv.writer(out_f)
for file_path in input_files:
with open(file_path, 'r', newline='', encoding=encoding) as in_f:
reader = csv.reader(in_f)
file_header = next(reader) # Assume all files have headers
if first_file:
header = file_header
if dedup_columns is not None:
try:
col_indices = [header.index(col) for col in dedup_columns]
except ValueError as e:
raise ValueError(f"Column not found in header: {e}")
writer.writerow(header) # Write header once
first_file = False
# Process data rows
for row in reader:
if dedup_columns is None or col_indices is None:
row_key = tuple(row)
else:
row_key = tuple(row[i] for i in col_indices)
if row_key not in seen:
seen.add(row_key)
writer.writerow(row)
Key Features:
Memory Efficient: Streams input files row-by-row, only storing unique keys (tuples) in a set. Full row dedup uses full row tuples; column-based uses smaller keys.
Handles Large Files: No full loading into memory (unlike pd.concat). Suitable for GB-scale files as long as unique rows/keys fit in RAM.
Preserves Order: Outputs rows in the order of first appearance across files.
Robust Header Handling: Uses first file's header; skips headers in subsequent files.
Flexible Deduplication: Exact rows or subset of columns (e.g., primary key).
Stdlib Only: Uses only Python standard library (csv module), no external dependencies like pandas.