Import and Export in Python



Python Tutorial 3.0


So far we have learnt creating data frame, defining variable and some data manipulation after hard coding the data. But practically, we do not define the data like that, we generally import the external data and then work on it.

We should know "How to import and export the data files" and we would learn the same in this article.


Let's import then!!!

Data :  Please copy and paste the below data in an excel and save the same as a .csv file. Try to import the same using following commands.

Name Age_Category Income_Category Marital_Status
Rajat 25-30 20-25 M
Vinod 30-35 10-15 M
Amit 25-30 15-20 S
Suresh 20-25 10-15 S
Dinesh 30-35 10-15 M
Ganesh 35-40 10-15 M


# Importing Pandas library

import pandas as p



Read and Write CSV file
# Define Variables

path = 'C:\\data_for_matrix.csv'


# Reading the file

sample=p.read_csv(path) 

sample


Output :

We can see that a data frame has been generated .





 Lets's now learn how to export any file

# Export/Write csv file

sample.to_csv('C:\\data_for_matrix1.csv')



Read and Write Txt file

Copy same data given above and paste it in txt file(data).


# Reading the file

sample=p.read_table('C:\\data.txt'

# Export/Write txt file


sample.to_csv(r'C:\\data1.txt',header=None,index=None,sep=',')



Enjoy reading our other articles and stay tuned with us.

Kindly do provide your feedback in the 'Comments' Section and share as much as possible.