Education, Learning, Technology

Using Python to Read a csv file

Program:

import csv

# Ensure the csv file is placed in the same directory as the script.
# If file is in a different directory give the full path
# To keep the code simple, No checks are made on file existence before reading the file.

DATA_FILE_NAME = 'ppd_data.csv'
print('Get File handler')
fh = open(DATA_FILE_NAME, 'rU')
# Read csv file using the file handler
csvParsed = csv.reader(fh)
line_list = []
for row in csvParsed:
    line_list.append(row)

print('Printing Data in CSV file')
print(line_list)
print('Total Rows:' + str(len(line_list)))

# Display only certain elements of a list
# For example display only price paid and property type

for item in line_list:
    print(item[1] + '   '+item[4])

# AS the Data is in a list, you can do aggregation
# For example Display how many properties are sold per type
dcount = 0
scount = 0
tcount = 0
ocount = 0
for item in line_list:
        if item[4] == 'D':
            dcount = dcount + 1
        elif item[4] == 'S':
            scount = scount + 1
        elif item[4] == 'T':
            tcount = tcount + 1
        else:
            ocount = ocount + 1 ## This is the header row.

print('Count of Detatched Houses Sold:' + str(dcount))
print('Count of Semi Detatched Houses Sold:' + str(scount))
print('Count of Terraced Houses Sold:' + str(tcount))
print('Count of Other Houses Sold:' + str(ocount))

Sample Data: Source UK  Land Registry

unique_id,price_paid,deed_date,postcode,property_type,new_build,estate_type,saon,paon,street,locality,town,district,county,transaction_category
453D27A3-87D8-EF91-E050-A8C0630574D7,870000,22/11/2016,GU15 1AD,D,N,F,,5,CHESTERS ROAD,,CAMBERLEY,SURREY HEATH,SURREY,A
42A5A709-BF28-56E8-E050-A8C06205331E,675000,21/11/2016,GU15 1AF,D,N,F,,16,DUNDAFF CLOSE,,CAMBERLEY,SURREY HEATH,SURREY,A
42A5A709-BD57-56E8-E050-A8C06205331E,630000,03/11/2016,GU15 1AL,D,N,F,,7,YOULDEN DRIVE,,CAMBERLEY,SURREY HEATH,SURREY,A
42A5A709-BBBF-56E8-E050-A8C06205331E,535000,13/10/2016,GU15 1AQ,D,N,F,,6,LANGDON CLOSE,,CAMBERLEY,SURREY HEATH,SURREY,A
453D27A3-8794-EF91-E050-A8C0630574D7,395000,25/11/2016,GU15 1BL,T,N,F,,5,SHILDON CLOSE,,CAMBERLEY,SURREY HEATH,SURREY,A
47844C80-52C1-8986-E050-A8C063056488,300000,09/12/2016,GU15 1BN,T,N,F,,3,TROUTBECK WALK,,CAMBERLEY,SURREY HEATH,SURREY,A

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s