Python to Merge CSV Files with Full Source Code

Merge CSV Files:

With the help of the following simple python script, one would be able to merge CSV files present in the directory.

Dependencies:

  • Requires Python 3 and pandas

Install requirements: 

pip install -r "requirements.txt"Code language: JavaScript (javascript)

 OR

Install pandas: 

pip install pandas

How to Use:

  • Put all the CSVs which are to be merged in a directory containing the script. either run it from your code editor or IDE or type 
python merge_csv_files.pyCode language: CSS (css)
  • The final output would be a combined_csv.csv file in the same directory.

Source Code:

merge_csv_files.py

import glob
import pandas as pd

extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]

combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ])
combined_csv.to_csv( "combined_csv.csv", index=False, encoding='utf-8-sig')Code language: JavaScript (javascript)

Leave a Comment