import pandas as pd
import glob
# ---
# Step 1: Specify Settings
# ---
# Path to your CSV files (can be a directory with a wildcard or specific file paths separated by commas)
csv_path = 'path/to/your/csv/files/*.csv' # For files in a directory
# csv_path = 'file1.csv, file2.csv, file3.csv' # For specific file paths
# Common column(s) to join on (separate multiple columns with commas, no spaces)
common_columns = 'id' # Single column
# common_columns = 'column1,column2' # Multiple columns
# Type of join (options: 'inner', 'left', 'right', 'outer')
join_type = 'inner'
# Output file name
output_file = 'combined_output.csv'
# ---
# Step 2: Load CSV Files
# ---
def load_csv_files(path):
"""
Load CSV files based on the provided path.
If a directory path with a wildcard is used, it loads all matching files.
If specific file paths are comma-separated, it loads those files.
"""
try:
if ',' in path:
# If specific file paths are provided
files = [file.strip() for file in path.split(',')]
# Check if files exist
for file in files:
if not glob.glob(file):
print(f"Warning: File '{file}' not found. Skipping...")
files = [file for file in files if glob.glob(file)]
else:
# If a directory path with a wildcard is provided
files = glob.glob(path)
if not files:
print(f"Warning: No files found at '{path}'.")
return files
except Exception as e:
print(f"Error loading files: {e}")
return []
# ---
# Step 3: Combine CSV Files
# ---
def combine_csv_files(files, common_cols, join_type):
"""
Combine the loaded CSV files using the specified common columns and join type.
"""
try:
# Convert common_columns to list if multiple
common_cols = [col for col in common_cols.split(',')]
if not files:
print("No files to combine.")
return None
# Load the first file
combined_df = pd.read_csv(files[0])
# Check if common columns exist in the first file
for col in common_cols:
if col not in combined_df.columns:
print(f"Error: Column '{col}' not found in the first file. Please check column names.")
return None
# Iterate through the remaining files and join
for file in files[1:]:
df = pd.read_csv(file)
# Check if common columns exist in subsequent files
for col in common_cols:
if col not in df.columns:
print(f"Error: Column '{col}' not found in '{file}'. Skipping this file.")
continue
# Ensure data types of common columns match
for col in common_cols:
combined_df[col] = pd.to_numeric(combined_df[col], errors='coerce')
df[col] = pd.to_numeric(df[col], errors='coerce')
combined_df = pd.merge(combined_df, df, on=common_cols, how=join_type)
return combined_df
except Exception as e:
print(f"Error combining files: {e}")
return None
# ---
# Step 4: Execute and Save
# ---
if __name__ == "__main__":
files = load_csv_files(csv_path)
print(f"Loaded files: {files}")
if len(files) < 2:
print("At least two CSV files are required for merging.")
else:
combined_df = combine_csv_files(files, common_columns, join_type)
if combined_df is not None:
combined_df.to_csv(output_file, index=False)
print(f"Files combined and saved to: {output_file}")