12

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
martineau
  • 119,623
  • 25
  • 170
  • 301
atul
  • 183
  • 1
  • 1
  • 7
  • what is the error ur getting? – Srinivas Reddy Thatiparthy Apr 26 '11 at 09:40
  • 1
    The code looks fine to me. Without the error, or the contents of 'some.csv' it is difficult to help. – juanchopanza Apr 26 '11 at 09:43
  • with open('some.csv', 'rb') as f showing syntax error as invalid syntax – atul Apr 26 '11 at 09:44
  • the error given is some **basic information** you should give if you want to get an answer for a question like this. – pconcepcion Apr 26 '11 at 09:48
  • 11
    sheesh, guys, some patience for a new user. If you don't have anything constructive to say, leave your jokes for the pub – Eli Bendersky Apr 26 '11 at 09:52
  • @atul: Please copy and paste the output into your question. Please **update** the question with the actual error message you're actually getting. All of it. – S.Lott Apr 26 '11 at 09:54
  • I get the following error with your code: `IOError: [Errno 2] No such file or directory: 'some.csv'`, not one that says `invalid syntax`. This means means it could not find the referenced .csv file. Is that your error? – martineau Apr 26 '11 at 12:01
  • Possible duplicate of [How do I read and write CSV files with Python?](http://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – Martin Thoma Jan 11 '17 at 07:45

2 Answers2

18

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

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 1
    @atul: Please do not bury important information in a comment. Please **update** the question to contain **all** the facts. – S.Lott Apr 26 '11 at 09:55
6
from __future__ import with_statement

And if that doesn't work, rewrite it to not use with in the first place.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358