CSV File filtering using django(python)

Here is an csv file below:

"header1","header2","header3"
0.051267,0.69956,1
-0.51325,0.46564,1
0.085829,-0.75512,0
0.14919,-0.57968,0
0.13767,0.57529,1
-0.0063364,0.39985,1
-0.092742,0.55336,1

I want to pick up the records where column "header 3" equals 0. But I get a KeyError when running line 7.

Error text:

Request Method: GET
Request URL:    http://127.0.0.1:8000/filter/
Django Version: 1.8.3
Exception Type: KeyError
Exception Value:2
Exception Location: C:\Users\antsy\Desktop\datahub-master\view\showdata.py in csv_Filter, line 7
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.10

Python code:

def csv_Filter(request):
writer = csv.writer(file(r'test\temp.txt', 'wb'))
with open(r'test\ex2data2.txt', 'rb') as f:
    reader = csv.DictReader(f)
    writer.writerow(f.read(0))
    for row in reader:
        if row[2] == 0:
            writer.writerow(row)
reader = file(r'test\temp.txt', 'rb')
respond = showTable(request, r'test\temp.txt', reader) #another def
return respond

Answers


This will do the trick:

import csv

with open('source.csv', 'rb') as source_csv:
    with open('target.csv', 'wb') as target_csv:
        reader = csv.DictReader(source_csv)
        writer = csv.DictWriter(target_csv, fieldnames = reader.fieldnames)
        writer.writeheader()
        for row in reader:
            if row['header3'] == '0':
                writer.writerow(row)

It generates the following file:

header1,header2,header3
0.085829,-0.75512,0
0.14919,-0.57968,0

Please have a look at the csv module documentation for more examples.


Need Your Help

Java array with unknow size - what's wrong?

java arrays class nullpointerexception

ImageItem imageItems[] = new ImageItem[data.length()];

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.