Export Read Delete CSV File Using Pandas Module of Python

Export Read Delete CSV File Using Pandas Module of Python

Instructor-svgAl-Mamun Sarkar
Apr 01 , 2020

Export Read Delete CSV File Using Pandas Module of Python. The following shows how to read form csv file, write data to csv and delete csv file using pandas module.

 

Importing Module:

import pandas as pd
import sys

 

Creating Data:

Code:

names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]

BabyData = list(zip(names, births))
BabyData

Output:

[('Bob', 968), ('Jessica', 155), ('Mary', 77), ('John', 578), ('Mel', 973)]

 

Making DataFrame:

Code:

df = pd.DataFrame(data = BabyData, columns=['Names', 'Births'])
df

Output:

  Names Births
0 Bob 968
1 Jessica 155
2 Mary 77
3 John 578
4 Mel 97

 

Export the dataframe to a csv file:

df.to_csv('Data/births.csv', index=False, header=False)
df.to_csv('Data/births1880.csv', index=False, header=['Names', 'Births'])

 

Get Dataframe for a csv file:

ndf = pd.read_csv('Data/births.csv', header=None)
ndf

Output:

  0 1
0 Bob 968
1 Jessica 155
2 Mary 77
3 John 578
4 Mel 973

 

ndf = pd.read_csv('Data/births.csv', names=['Names', 'Births'])
ndf

 Output:

  Names Births
0 Bob 968
1 Jessica 155
2 Mary 77
3 John 578
4 Mel 973

 

Delete CSV file:

import os
os.remove('Data/births1880.csv')

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram