Considering a deduplication function
The user wants a Python function to merge and deduplicate large CSV files, and I need to keep in mind the potential memory limitations. I think I should consider using Pandas with a chunksize or csv.DictReader with hashing and temporary files. For extremely large files, an external sort might be necessary, or I could process the data line by line into SQLite. It seems wise to propose a robust function using Pandas and on-disk deduplication to manage memory effectively.Designing a CSV deduplication function
I need to consider that for large datasets, like millions of entries, storing all hashes could lead to memory issues. A better approach is to use SQLite for deduplication because it manages memory more effectively. I’ll design a function that streams data into an SQLite table with a UNIQUE constraint on key columns, and then export the results to a CSV file. I think providing both moderate-sized solutions using Pandas and larger ones using SQLite is ideal, but I’ll lean towards giving one strong solution.Outlining deduplication steps
I'm starting by determining the header and columns from the first CSV file and reusing that structure for the others while verifying it. Then, I’ll create a SQL table with a UNIQUE constraint on the key columns. For each file, I'll skip the header, iterate through the rows, and use an "INSERT OR IGNORE" statement to avoid duplicates. After processing, I'll select all rows, order them, and write everything to the output file. I can also support deduplication based on entire rows if key_columns is None, but keep in mind SQLite’s column limit.Designing the function signature
I'm defining a function called merge_and_deduplicate_csv, which will take parameters like input paths, output path, key columns, encoding, delimiter, quote character, and an optional temporary database path. The key_columns will determine if I should deduplicate by specific columns or the full row if it’s set to None. I also plan to ensure that table and column names are properly quoted and formatted, replacing spaces with underscores while keeping the original header names for clarity. I'll also account for any double quotes in headers by doubling them, though that could complicate things a bit.Finalizing function implementation details
I'm considering using generic column names like col0, col1, but mapping them to sanitized key names would be more intuitive, especially since key_columns are specified by name. When sanitizing, I can replace non-word characters and double quotes appropriately for SQLite compatibility. I'll define a function to quote identifiers correctly, which will help when creating the table.
Next, I’ll import necessary modules and set up the main function, ensuring proper validation of headers across all files. Each file will be processed once to avoid redundancy.
For insertion, I’ll prepare SQL queries using placeholders for efficiency and handle large datasets by committing every 50,000 rows. Finally, I’ll export the merged data, ensuring the output maintains the correct column orders. I’ll also note the memory efficiency of this method and mention how results might not preserve original order unless explicitly ordered.Implementing order management and code snippet
I need to clarify that in SQLite, every table has a ROWID by default, unless specified otherwise. So, I can use SELECT {columns_sql} FROM data ORDER BY rowid; to maintain the insertion order while ignoring duplicates. I’ll include an optional boolean parameter, preserve_order; if set to True, I’ll sort by rowid, otherwise, it’ll run faster without the sort.
Since we're focusing on large CSV files, I’ll highlight the importance of streaming data rather than reading everything into memory. I want to keep comments concise while providing a thorough docstring about the function parameters, so I'll get started on crafting that final implementation. Here is a scalable, memory‑efficient way to merge and deduplicate large CSV files using SQLite as a temporary on‑disk store.
import csv
import sqlite3
import tempfile
from pathlib import Path
from typing import Iterable, List, Optional, Union
def merge_and_deduplicate_csv(
input_paths: Iterable[Union[str, Path]],
output_path: Union[str, Path],
key_columns: Optional[List[str]] = None,
*,
encoding: str = "utf-8",
delimiter: str = ",",
quotechar: str = '"',
preserve_input_order: bool = False,
) -> None:
"""
Merge multiple CSV files and remove duplicate rows, streaming from disk.
Parameters
----------
input_paths : iterable of str or Path
Paths to input CSV files. All must have the same header.
output_path : str or Path
Path to the merged, deduplicated CSV.
key_columns : list of str, optional
Column names that define a "duplicate". If None, the entire row
must match to be considered a duplicate.
encoding : str, default "utf-8"
File encoding for input and output.
delimiter : str, default ","
CSV delimiter.
quotechar : str, default '"'
CSV quote character.
preserve_input_order : bool, default False
If True, output rows are returned in the order they were first seen
(first occurrence wins). If False, order is not guaranteed but may
be slightly faster.
Notes
-----
- Handles large files by streaming into a temporary SQLite database.
- Deduplication is enforced with a UNIQUE constraint on key_columns.
"""
input_paths = [Path(p) for p in input_paths]
if not input_paths:
raise ValueError("No input files provided.")
# --- Helper: quote SQLite identifiers safely ---
def quote_ident(name: str) -> str:
return '"' + name.replace('"', '""') + '"'
# --- 1. Read and validate headers ---
# Use the header from the first file as the canonical header.
with input_paths[0].open("r", encoding=encoding, newline="") as f:
reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar)
try:
header = next(reader)
except StopIteration:
raise ValueError(f"First file {input_paths[0]} is empty.")
if not header:
raise ValueError("Header row is empty.")
# Validate that all files share the same header
for path in input_paths[1:]:
with path.open("r", encoding=encoding, newline="") as f:
reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar)
try:
other_header = next(reader)
except StopIteration:
raise ValueError(f"Input file {path} is empty.")
if other_header != header:
raise ValueError(
f"Header mismatch in file {path}.\n"
f"Expected: {header}\n"
f"Found: {other_header}"
)
# Validate key columns
if key_columns is not None:
missing = [c for c in key_columns if c not in header]
if missing:
raise ValueError(f"key_columns not in header: {missing}")
unique_cols = key_columns
else:
# Deduplicate on full row
unique_cols = header
# --- 2. Create temporary SQLite DB and table with UNIQUE constraint ---
temp_db_file = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
temp_db_path = temp_db_file.name
temp_db_file.close()
conn = sqlite3.connect(temp_db_path)
cur = conn.cursor()
# Some pragmas to speed up bulk inserts (safe for a throwaway DB)
cur.execute("PRAGMA journal_mode = OFF;")
cur.execute("PRAGMA synchronous = OFF;")
cur.execute("PRAGMA temp_store = MEMORY;")
col_defs = ", ".join(f"{quote_ident(col)} TEXT" for col in header)
unique_clause = ", ".join(quote_ident(c) for c in unique_cols)
create_sql = f"""
CREATE TABLE data (
{col_defs},
UNIQUE ({unique_clause})
);
"""
cur.execute(create_sql)
conn.commit()
columns_sql = ", ".join(quote_ident(c) for c in header)
placeholders = ", ".join("?" for _ in header)
insert_sql = f"INSERT OR IGNORE INTO data ({columns_sql}) VALUES ({placeholders})"
# --- 3. Stream rows from each CSV into SQLite ---
batch_size = 10_000
batch = []
for path in input_paths:
with path.open("r", encoding=encoding, newline="") as f:
reader = csv.DictReader(f, delimiter=delimiter, quotechar=quotechar)
# DictReader reads header automatically and skips it
for row in reader:
# Preserve column order as in header
values = [row.get(col, None) for col in header]
batch.append(values)
if len(batch) >= batch_size:
cur.executemany(insert_sql, batch)
conn.commit()
batch.clear()
if batch:
cur.executemany(insert_sql, batch)
conn.commit()
batch.clear()
# --- 4. Export deduplicated data to output CSV ---
order_clause = "ORDER BY rowid" if preserve_input_order else ""
select_sql = f"SELECT {columns_sql} FROM data {order_clause};"
output_path = Path(output_path)
with output_path.open("w", encoding=encoding, newline="") as f_out:
writer = csv.writer(f_out, delimiter=delimiter, quotechar=quotechar)
writer.writerow(header)
for row in cur.execute(select_sql):
writer.writerow(row)
# --- 5. Clean up ---
conn.close()
Path(temp_db_path).unlink(missing_ok=True)
Usage example
merge_and_deduplicate_csv(
input_paths=["data1.csv", "data2.csv", "data3.csv"],
output_path="merged_deduped.csv",
key_columns=["id"], # deduplicate by ID
preserve_input_order=True, # keep first-seen row for each ID
)
- If you want to deduplicate entire rows (every column must match), pass
key_columns=None (the default).
- This approach scales to very large files because:
- Rows are streamed from CSV → SQLite → CSV.
- Only small batches stay in memory at any time.
- Deduplication is enforced by a UNIQUE constraint in SQLite.