Skip to content

Instantly share code, notes, and snippets.

@fitoprincipe
Last active August 10, 2021 15:50
Show Gist options
  • Save fitoprincipe/67df15dfc7f57adb96c1c1de79ef210f to your computer and use it in GitHub Desktop.
Save fitoprincipe/67df15dfc7f57adb96c1c1de79ef210f to your computer and use it in GitHub Desktop.
import csv, glob, argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", help="name of the resulting file")
args = parser.parse_args()
csv_list = glob.glob('*.csv')
result_name = args.name or 'merged.csv'
# get fieldnames
with open(csv_list[0], newline='') as csvfile:
reader = csv.DictReader(csvfile)
fieldnames = reader.fieldnames
# merge
with open(result_name, 'w+', newline='') as thewrite:
writer = csv.DictWriter(thewrite, fieldnames=fieldnames)
writer.writeheader()
for file in csv_list:
with open(file, newline='') as theread:
reader = csv.DictReader(theread)
for row in reader:
writer.writerow(row)
@fitoprincipe
Copy link
Author

All CSV file must have the same column names. It takes the columns names from the first CSV file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment