The user wants a Python function to merge and deduplicate large CSV files.
"Large" is the key constraint here. Reading entire files into memory (like using pandas.concat or loading everything into a list of dictionaries) might cause MemoryError.
Approaches for "Large" files:
Chunking with Pandas: Pandas has a chunksize parameter in read_csv. I can read a chunk, process it, and write it out. However, deduplication usually requires comparing rows across files or keeping track of seen rows. If I just process chunks independently, I might miss duplicates if a row appears in file A, chunk 1 and file B, chunk 2.
Streaming/Generator approach (Standard Library csv): This is memory efficient. Open files one by one (or all at once using heapq if sorting is needed, but let's stick to simple merging first).
Deduplication Strategy:
Strategy A (Exact Row Match): Keep a set of hashes (e.g., MD5 or tuple of values) of rows seen so far. If a row's hash is in the set, skip it. Else, write to output and add to set.
Problem: If the dataset is massive, the set of hashes might still exceed memory.
Strategy B (Sorting then deduping): If we can sort the data, duplicates become adjacent. This is the standard external sort approach.
Step 1: Sort-merge the files.
Step 2: Iterate through the sorted stream. If current row == previous row, skip.
Strategy C (Database): Load into SQLite/Postgres/DuckDB. Let the DB handle it. This is often the most robust way for truly large data, but might be overkill if the user just wants a script.
Strategy D (Pandas Chunking + Temporary Storage): Read chunks, dedupe within chunk, write to temp files. Then merge temp files.
Let's evaluate the user's likely needs:
Usually, when people ask for "large CSV files" in Python without specific size (like 1TB), they mean files that don't fit in RAM (e.g., 2GB, 5GB, 10GB) but might fit on disk.
The most robust general-purpose Python solution:
Using a database (SQLite) is the easiest code-wise and handles disk-spilling automatically.
However, a pure algorithmic approach using the standard csv module is often preferred for portability and no dependencies.
Let's try the Hash Set approach first. It works great until the uniqueness set fills up RAM.
Let's try the Pandas approach (most common for data tasks).
Correction: If the data is truly large, Pandas is often memory hungry even with chunks if the logic is complex. The csv module is leaner.
Let's design a solution that balances simplicity and efficiency.
I will provide two solutions:
The "Medium-Large" Solution (Pandas): Good for files up to a few GBs, assuming the user likes Pandas. It uses chunking. But wait, chunking makes cross-file deduplication hard.
The "Robust" Solution (Streaming with a Set): Uses the csv module. It reads row by row.
Constraint: It keeps a set() of identifiers. If the number of unique rows is huge (millions/billions), this crashes RAM.
The "External Sort" Solution (Unix philosophy): Sort all files, then stream. This is the most memory-safe. Python's heapq.merge can help if files are pre-sorted, but sorting large files in Python is slow.
Let's stick to the most practical interpretation:
Usually, "deduplicate" implies checking specific columns (keys) or the whole row.
Plan:
I will implement a generator-based solution using the standard csv library. It will maintain a set of "seen" identifiers.
To handle the "Large" aspect better, I will offer a specific strategy: Checkpointing/Streaming to Disk (SQLite) or just Streaming with a Set (with a warning about RAM).
Actually, the best generic "Pythonic" way for large files that might exceed RAM for the seen set is using DuckDB or SQLite. But the user asked for a Python function.
Let's go with a Stream + Hash Set approach. This covers 90% of "Large CSV" use cases (files are big, but the number of unique rows or keys fits in memory). If the number of unique rows is too big for RAM, simple Python sets won't work anyway without external storage.
Refining the Stream + Hash Set approach:
Inputs: list of filenames, output filename, list of column names to use as unique key (optional).
Open output file for writing.
Initialize a set seen_keys.
Loop through input files.
Loop through rows in current file.
Construct a unique identifier (tuple or hash) based on specific columns or the whole row.
If identifier in seen_keys, continue.
Else, write row, add to seen_keys.
Handling Headers:
We need to ensure we only write the header once. We should assume all files share the same schema.
Alternative: Pandas solution.
Many users expect Pandas.
pd.read_csv(f, chunksize=10000).
Accumulate chunks, drop duplicates, write to output.
Issue: Same as before. If duplicate exists in chunk 1 and chunk 100, chunk-based dropping misses it unless we keep the history.
Decision: I will provide a solution using the standard csv library (memory efficient for row streaming) and a simple hashing mechanism. I will also add a "Pro" tip about using DuckDB/SQLite for massive datasets where the keys don't fit in RAM.
Code Structure:
Function merge_and_deduplicate(input_files, output_file, key_columns=None)
key_columns=None: means check whole row.
key_columns=['id']: means check specific columns.
Optimization: Storing the whole row string in the set is memory intensive. Storing a hash (e.g., md5) of the row/key reduces memory footprint significantly.
Step-by-Step Implementation:
Import csv, hashlib.
Define function.
Open output file with newline=''.
Initialize writer.
Initialize seen_hashes = set().
Flag header_written = False.
Iterate through input_files.
Open input file.
Reader object.
Handle header row (write on first encounter, skip on others).
Iterate rows.
Create string to hash: row values or specific columns.
Hash it (md5/sha1 is faster than generic python hashing for large strings? actually python hash is fast, but for sets, we need the value. Python tuples of strings in a set use the strings themselves. MD5 reduces size to 32 chars. If keys are short, keep as is. If long, hash). Let's stick to tuples of column values for simplicity, or string join. String join is safest for the set.
Let's refine the Hashing. If a row has 100 columns, making a tuple is heavy.
hashlib.md5(str(row).encode()).hexdigest() is a good trade-off for memory.
Refining requirements:
The user asked for large files.
Reading line by line is crucial.
Code needs to handle file opening/closing correctly.
Final Plan:
Primary Solution: Standard library csv. Memory efficient streaming. Uses a hash set to track seen rows/keys.
Caveat: Warns about seen_hashes memory usage.
Alternative (SQLite): Briefly mention or implement a fallback if data is truly massive (exceeds RAM for keys). Actually, let's stick to the pure Python one but make it robust.
Let's write the code.
python
Reviewing the code logic:
Uses DictReader (handles headers automatically).
Handles schema detection from first file.
Uses hashlib.md5 to keep the memory footprint of seen_hashes low.
Input/Output encoding set to utf-8 (standard).
Handles key_columns.
"Large" files: This streams line-by-line. It does not load the whole file. The only memory consumer is seen_hashes.
Corner case: What if seen_hashes gets too big?
If the file is 100GB and has 500 million unique rows:
A set of 500M MD5 digests (16 bytes) -> 8GB RAM + Python object overhead. It might crash on a 16GB machine.
However, without an external database or sorting, this is the limit of a pure Python in-memory approach. I should mention this limit.
Is there a way to fix the memory limit?
Yes, External Sort (Sort -> Merge -> Dedup).
It's much more complex to implement in a single function (requires writing temp files).
Or use DuckDB. duckdb.sql("SELECT DISTINCT * FROM read_csv_auto('*.csv')").
DuckDB is excellent for this. It handles streaming and large data better than pandas.
Maybe I should offer the DuckDB solution as an alternative for "True Big Data".
Let's provide:
The robust standard library solution (streaming + hashing).
A mention of the Pandas approach (easier syntax but more memory heavy).
A mention of the DuckDB approach (best for performance/large data).
I will refine the standard library code to be production-ready.
Use DictWriter with extrasaction='ignore'? No, explicit construction clean_row is safer.
key_data generation: If keys are missing, it might produce weird results. row.get(col, '') is safer.
Final Polish of the Code Snippet:
Include imports.
Docstring.
Example usage block.
Comment on memory usage.
Let's create the final response.
When dealing with large CSV files, the primary constraint is memory (RAM). You cannot load the entire files into a DataFrame or a list because you will run out of memory.
The most robust, memory-efficient approach uses Python's built-in csv library to stream the files line-by-line. To handle deduplication efficiently, we use a set to store a hash (like MD5) of the unique identifiers or row contents, rather than the data itself.
Here is a complete, robust solution.
The Solution (Streaming Approach)
This function reads input files one row at a time, keeping only a set of "seen" hashes in memory. This allows you to merge files that are significantly larger than your available RAM.
python
How it handles "Large" files
Streaming (csv.DictReader): It reads the input file one line at a time. It never loads the whole file into memory.
Hashing (hashlib.md5): If you are deduplicating based on a long text field (e.g., a product description), storing that text in a Python set will eat up RAM. By hashing the text into a 32-character hex string, the seen_hashes set remains tiny regardless of how large the data is.
Alternative: The "SQL" Approach (For Massive Datasets)
If your files are so massive (e.g., 50GB+) that even the set of MD5 hashes doesn't fit in RAM, you should use SQLite. SQLite is a disk-based database, so it uses your hard drive instead of RAM.
Here is the logic for the SQLite approach:
Create a temporary SQLite database file on disk.
Create a table with a UNIQUE index on the columns you care about.
Stream the CSVs into the SQLite table (SQLite will handle the deduplication logic automatically).
Dump the SQLite table back to a CSV.
Quick implementation snippet:
python
import sqlite3
import csv
def merge_with_sql(input_files, output_file, unique_col):
# Connect to a temporary file on disk
conn = sqlite3.connect("temp_merge.db")
cursor = conn.cursor()
# Create table (adjust types as needed)
cursor.execute(f"CREATE TABLE data ({unique_col} TEXT PRIMARY KEY, content TEXT)")
for file in input_files:
with open(file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
# 'INSERT OR IGNORE' will skip duplicates automatically
# You might need to serialize row data into 'content' or make specific cols
cursor.execute(
f"INSERT OR IGNORE INTO data ({unique_col}) VALUES (?)",
(row[unique_col],)
)
conn.commit()
# Write back to CSV
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow([unique_col]) # Header
for row in cursor.execute("SELECT * FROM data"):
writer.writerow(row)
conn.close()
os.remove("temp_merge.db")
import csv
import hashlib
import os
def merge_and_deduplicate_csv(input_files, output_file, key_columns=None, delimiter=','):
"""
Merges multiple CSV files and removes duplicates.
Args:
input_files (list): List of paths to input CSV files.
output_file (str): Path to the output CSV file.
key_columns (list, optional): List of column names to use for deduplication.
If None, checks the entire row.
delimiter (str): Delimiter character (default ',').
"""
seen_hashes = set()
header = None
rows_written = 0
with open(output_file, 'w', newline='', encoding='utf-8') as out_f:
writer = None
for file_path in input_files:
# Check if file exists to avoid crashing
if not os.path.exists(file_path):
print(f"Warning: File {file_path} not found. Skipping.")
continue
with open(file_path, 'r', newline='', encoding='utf-8') as in_f:
reader = csv.DictReader(in_f, delimiter=delimiter)
# Capture header from the first file
if header is None:
header = reader.fieldnames
# Initialize writer once we have the header
writer = csv.DictWriter(out_f, fieldnames=header, delimiter=delimiter)
writer.writeheader()
# Safety check for mismatched schemas (simple check)
if reader.fieldnames != header:
# In a real prod scenario, we might map columns or error out.
# For this function, we just warn.
print(f"Warning: Schema mismatch in {file_path}. Expected {header}, got {reader.fieldnames}")
for row in reader:
# Determine unique key
if key_columns:
# Select specific columns for the key
# Handle missing keys gracefully
try:
key_data = "".join(str(row[col]) for col in key_columns)
except KeyError as e:
print(f"Warning: Key column {e} not found in row. Skipping row.")
continue
else:
# Use entire row content for uniqueness
key_data = "".join(str(v) for v in row.values())
# Hash the key to save memory in the set
# 16 bytes of MD5 is usually enough for deduplication
row_hash = hashlib.md5(key_data.encode('utf-8')).digest()
if row_hash not in seen_hashes:
seen_hashes.add(row_hash)
# Only write columns that are in the header to maintain schema
# If input has extra cols, they are ignored. If missing, error/empty.
# csv.DictWriter handles missing keys based on `extrasaction` (default 'raise')
# Let's be safe: construct a dict with only header keys
clean_row = {k: row.get(k, '') for k in header}
writer.writerow(clean_row)
rows_written += 1
print(f"Processing complete. Total rows written: {rows_written}")
import csv
import hashlib
import os
from typing import List, Optional
def merge_and_deduplicate_csv(
input_files: List[str],
output_file: str,
unique_columns: Optional[List[str]] = None,
delimiter: str = ','
):
"""
Merges large CSV files and removes duplicates using a memory-efficient stream.
Args:
input_files (List[str]): List of paths to input CSV files.
output_file (str): Path to the output CSV file.
unique_columns (Optional[List[str]]): Column names to determine uniqueness.
If None, checks the entire row content.
delimiter (str): The delimiter used in the CSV (default ',').
"""
seen_hashes = set()
header = None
rows_written = 0
duplicate_count = 0
# Open output file for writing
with open(output_file, 'w', newline='', encoding='utf-8') as out_f:
writer = None
for file_path in input_files:
if not os.path.exists(file_path):
print(f"Warning: File not found, skipping: {file_path}")
continue
try:
with open(file_path, 'r', newline='', encoding='utf-8') as in_f:
reader = csv.DictReader(in_f, delimiter=delimiter)
# 1. Handle Header Logic
current_file_header = reader.fieldnames
if header is None:
# First file: Set the master header and initialize writer
header = current_file_header
writer = csv.DictWriter(out_f, fieldnames=header, delimiter=delimiter)
writer.writeheader()
else:
# Subsequent files: Check for schema mismatch
if set(header) != set(current_file_header):
print(f"Warning: Schema mismatch in {file_path}. "
f"Expected {header}, got {current_file_header}. "
"Aligning columns (missing cols will be empty).")
# 2. Process Rows
for row in reader:
# Create a string representing the unique identity of the row
if unique_columns:
# Use specific columns
try:
identity_str = "|".join(str(row[col]) for col in unique_columns)
except KeyError as e:
print(f"Skipping row in {file_path}: Missing unique column {e}")
continue
else:
# Use entire row content
# Sort items to ensure {'a':1, 'b':2} is same as {'b':2, 'a':1}
identity_str = "|".join(f"{k}={v}" for k, v in sorted(row.items()))
# 3. Hashing
# We hash the identity string to save memory.
# Storing full strings in a set can consume GBs of RAM.
row_hash = hashlib.md5(identity_str.encode('utf-8')).hexdigest()
# 4. Deduplicate
if row_hash not in seen_hashes:
seen_hashes.add(row_hash)
# Ensure row matches output schema (fill missing with empty)
clean_row = {col: row.get(col, '') for col in header}
writer.writerow(clean_row)
rows_written += 1
else:
duplicate_count += 1
except Exception as e:
print(f"Error processing file {file_path}: {e}")
print(f"Processing complete.")
print(f"Total files processed: {len(input_files)}")
print(f"Total rows written: {rows_written}")
print(f"Duplicates removed: {duplicate_count}")
# --- Example Usage ---
if __name__ == "__main__":
# Create dummy data for demonstration
data1 = [
{'id': '1', 'name': 'Alice', 'age': '30'},
{'id': '2', 'name': 'Bob', 'age': '25'}
]
data2 = [
{'id': '2', 'name': 'Bob', 'age': '25'}, # Duplicate
{'id': '3', 'name': 'Charlie', 'age': '35'}
]
# Write dummy files
with open('file1.csv', 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=['id', 'name', 'age'])
w.writeheader()
w.writerows(data1)
with open('file2.csv', 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=['id', 'name', 'age'])
w.writeheader()
w.writerows(data2)
# Run the function
# Deduplicate based on 'id' column only
merge_and_deduplicate_csv(
['file1.csv', 'file2.csv'],
'merged_output.csv',
unique_columns=['id']
)