Home »
Python »
Python Programs
Reading two csv files and appending them into a new csv file
Learn how to read two csv files and appending them into a new csv file in Python?
By Pranit Sharma Last updated : October 06, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
CSV files or Comma Separated Values files are plain text files but the format of CSV files is tabular. As the name suggests, in a CSV file, each specific value inside the CSV file is generally separated with a comma. The first line identifies the name of a data column. The further subsequent lines identify the values in rows.
Col_1_value, col_2_value , col_3_value
Row1_value1 , row_1_value2 , row_1_value3
Row1_value1 , row_1_value2 , row_1_value3
Here, the separator character (,) is called a delimiter. There are some more popular delimiters. E.g.: tab(\t), colon (:), semi-colon (;) etc.
Reading two csv files and appending them into a new csv file
To read a CSV file in Pandas we use pandas.read_csv() method. To read multiple CSV files and append them into one CSV file we will first read both files using the pandas.read_csv() method and then we will use the contact method for appending the data inside them.
Finally, we will create a new CSV file by using the pandas.DataFrame.to_csv() method.
Let us understand with the help of an example,
Python program to read two csv files and appending them into a new csv file
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Reading two csv files
data1 = pd.read_csv('D:/mycsv.csv')
data2 = pd.read_csv('D:/mycsv1.csv')
# Creating a DataFrame
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# Display original DataFrame
print("Original DataFrame 1:\n",df1,"\n")
print("Original DataFrame 2:\n",df2,"\n")
# Appending dataframes and making a csv file
pd.concat([df1,df2]).to_csv('appended_csv.csv', index=False)
# Display result
print("CSV file created")
Output
The output of the above program is:
Python Pandas Programs »