Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a CSV file using Python

Tags:

python

csv

please tell me what's the problem in this code it's giving an error

import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row
like image 421
atul Avatar asked Apr 26 '11 09:04

atul


People also ask

Can you query a CSV file in Python?

querycsv -- Query a CSV File. querycsv.py is a Python module and program that allows you to execute SQL code against data contained in one or more comma-separated-value (CSV) files. The output of the SQL query will be displayed on the console by default, but may be saved in a new CSV file.


1 Answers

Which version of Python are you using?

The with statement is new in 2.6 - if you're using 2.5 you need from __future__ import with_statement. If you use a Python older than 2.5 then there's no with statement, so just write:

import csv
f = open('some.csv', 'rb')
reader = csv.reader(f)
for row in reader:
    print row
f.close()

It's really better to update to a modern version of Python, though. Python 2.5 was released almost 5 years ago, and the current version in the 2.x line is 2.7

like image 115
Eli Bendersky Avatar answered Sep 19 '22 18:09

Eli Bendersky