-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_data_merger.py
More file actions
42 lines (31 loc) · 1.27 KB
/
Copy pathcsv_data_merger.py
File metadata and controls
42 lines (31 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import csv # used to read and write CSV files
import glob # used to find files matching a pattern
# Folder containing your CSV files
# Example: "~/Downloads/reports/*.csv"
folder_path = "your/folder/path/*.csv" # IMPORTANT: include *.csv at the end
# Name of the final merged file
output_file = "master_report.csv"
# Find all CSV files in the folder
csv_files = glob.glob(folder_path)
# This will help us write the header only once
header_saved = False
# Open the output file in write mode
with open(output_file, "w", newline="") as outfile:
writer = None # we will create this after reading the first file
# Go through each CSV file
for file in csv_files:
print(f"Processing: {file}")
# Open each CSV file
with open(file, "r", newline="") as infile:
reader = csv.reader(infile)
# Read the header (first row)
header = next(reader)
# If we haven't written a header yet → write it
if not header_saved:
writer = csv.writer(outfile)
writer.writerow(header)
header_saved = True
# Write all remaining rows (data rows)
for row in reader:
writer.writerow(row)
print("All files merged into", output_file)