Sarath R Nair
Sarath R Nair

Reputation: 495

Error opening a csv file in python from a specific directory

I am very new to python and I am not having much experience in programming. I try to open a CSV file from a specific directory and I get error.

import csv
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");

Error:

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
IOError: [Errno 22] invalid mode ('rb') or filename: 'F:\\Study\\CEN\\Mini Project\\Data Sets\test.csv'

What to do ????

Upvotes: 1

Views: 13444

Answers (3)

Hexatonic
Hexatonic

Reputation: 2407

Your problem is with the "\t" AND a lack of exposure to various tools in the os.path package

The correct and easiest way to deal with this problem is to use os.path.normpath, combined with the string literal r, which ensures that backslashes are not interpreted as an escape character.

(Documentation on Lexical Analysis in python can be found here: https://docs.python.org/2/reference/lexical_analysis.html)

Open interactive python by typing "python" at the command line, and do the following to see that it's dead simple.

>>> import os
>>> path = r'F:\Study\CEN\Mini Project\Data Sets\test.csv'
>>> os.path.normpath(path)
'F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv'

normpath should be used when using hardcoded paths for scripts that may have to run on both dos and unix (eg OS X). It will ensure that the right kind of slashes are used for your particular environment

On a side note, if you are working with CSV files, you should use the petl library instead of the csv module. You'll save yourself a lot of time and hassle. Install it with pip install petl

Upvotes: 0

plsgogame
plsgogame

Reputation: 1344

Use forward slashes:

ifile = open('F:/Study/CEN/Mini Project/Data Sets/test.csv', "rb");

Or at least escape your backslashes:

ifile = open('F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv', "rb");

Another option: use os.path.join:

out = os.path.abspath(os.path.join('path', 'test.csv'))

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Your problem is here:

'F:\Study\CEN\Mini Project\Data Sets\test.csv'
                                    ^^

Because you did not use a raw string, Python thinks \t is supposed to mean a tab character.

You can see that in the error message, by the way: Notice how Python translated all the backslashes into double backslashes (which is how a literal backslash needs to be represented in a normal string) in all the places except the one where "backslash plus letter" actually meant something special?

Use

ifile = open(r'F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb")

(and remove the semicolons, you don't need them in Python) and it should work.

Upvotes: 2

Related Questions