Reading CSV file and Text File in Python

Reading Comma Separated (CSV) file in Python is one of the commonly used activities before proceeding to Data Science or Data Analysis steps.

We can read csv data at least two different ways.

# Read a csv file
import csv
path = 'C:\\Ram\\R for Data Science\\data\\'
file=open(path +"binary.csv")
reader = csv.reader(file)
# define length of columns
v1 = ["" for x in range(500)]
v2 = ["" for x in range(500)]
v3 = ["" for x in range(500)]
v4 = ["" for x in range(500)]
#  col names
cols =["" for x in range(4)]
b=0
# enumerate & read the file
for rows,l in enumerate(reader,1):
    b=b+1
    if(b==1):
        cols[0]=l[0]
        cols[1]=l[1]
        cols[2]=l[2]
        cols[3]=l[3]
    if(b>1):
        v1[b-2]=int(l[0])
        v2[b-2]=int(l[1])
        v3[b-2]=float(l[2])
        v4[b-2]=int(l[3])

# Create a data frame
df ={ cols[0]: v1[0:rows-1],
      cols[1]: v2[0:rows-1],
      cols[2]: v3[0:rows],
     cols[3]: v4[0:rows]
     }
df_csv= pd.DataFrame(df)

 

 

Reading CVS using function from Pandas Library.

import pandas as pd
binary= pd.read_csv('C:\\Ram\\R for Data Science\\data\\binary.csv')

 

 

Leave a Comment