1

I am encountering an issue while using the csv module.

Here is my code

import csv

out = open('C:\Python27\Work\test.csv')
data = csv.reader(out)
data = [row for row in data]
out.close()

print data

The error I get is thus:

Line 3 in module,
out = open('C:\Python27\Work\test.csv')
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Python27\\work\test.csv'

I'm confused because in the IOError it shows two backslashes (\) rather than one, which is very strange.

I've tried setting the mode to 'r', and 'rb' but nothing works.

When I use a different csv file, everything works just fine, and I get the output desired.

Harrison Boles
  • 733
  • 2
  • 6
  • 9
  • The error's not with the `csv` module. The error occurs when you open the file, before you pass it into `csv.reader`. As for the double backslashes, see the [documentation on string literals here](http://docs.python.org/2.0/ref/strings.html). – Joel Cornett Feb 11 '14 at 19:34
  • 1
    See this [post](http://stackoverflow.com/questions/15598160/ioerror-errno-22-invalid-mode-r-or-filename-c-python27-test-txt). Seems to be that `\t` is interpreted as a tab character. – David Feb 11 '14 at 19:37

2 Answers2

1

The problem is that \t is interpreted as a tab character. There are two ways to fix this problem:

Change:

 'C:\Python27\Work\test.csv'

To a raw string

 r'C:\Python27\Work\test.csv'

Or escape the backslashes:

 'C:\\Python27\\Work\\test.csv'
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
  • Sure. Windows paths tend to be problematic because the path separator happens to be a common escape character in programming. – Joel Cornett Feb 11 '14 at 20:02
-1

Two bugs:

  1. In Windows you need scape the backslash: out = open('C:\\Python27\\Work\\test.csv')
  2. By default the file is opened only read, when you assign the list to data variable, you are assigning the list to the csv-file object. Change the the variable name like this: my_data = [row for row in data]
Trimax
  • 2,413
  • 7
  • 35
  • 59
  • @JoelCornett `data` isn't the name of the csv.reader? He's duplicated the name of the variable. – Trimax Feb 11 '14 at 19:39
  • `data = csv.reader(out); data = [row for row in data]` works perfectly fine, although I would have prefered `data = list(csv.reader(out))` – Steinar Lima Feb 11 '14 at 19:42
  • 1
    While reassigning names is generally not a good programming practice, it won't cause an error in this script. If you don't believe me, try it yourself. – Joel Cornett Feb 11 '14 at 19:43
  • Also, your explanation of what is happening is incorrect. You aren't assigning anything to the CSV reader, you're merely changing what `data ` refers to. – Joel Cornett Feb 11 '14 at 19:45
  • @JoelCornett, you are all right. I tried it myself and that don't generate an error. – Trimax Feb 11 '14 at 19:49