Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error "no such file or directory" when reading in csv file in python

Currently I am trying to read in a csv file using the csv module in python. When I run the piece of code below I get an error that states the file does not exist. My first guess is that maybe, I have the file saved in the wrong place or I need to provide pyton with a file path. currently I have the file saved in C:\Documents and Settings\eag29278\My Documents\python test code\test_satdata.csv.

one side note im note sure wether having set the mode to 'rb' (read binary) was the right move.

import csv
with open('test_satdata.csv', 'rb') as csvfile:
    satreader = csv.reader(csvfile, delimiter=' ', lineterminator=" ")
    for row in satreader:
        print ', '.join(row)

Here is the errror code.

Traceback (most recent call last):
File "C:/Python27/test code/test csv parse.py", line 2, in <module>
    with open('test_satdata.csv', 'rb') as csvfile:
IOError: [Errno 2] No such file or directory: 'test_satdata.csv'
like image 691
erik.garcia294 Avatar asked Aug 05 '13 16:08

erik.garcia294


Video Answer


1 Answers

Your code is using a relative path; python is looking in the current directory (whatever that may be) to load your file. What the current directory is depends on how you started your Python script and if you executed any code that may have changed the current working directory.

Use a full absolute path instead:

path = r'C:\Documents and Settings\eag29278\My Documents\python test code\test_satdata.csv'
with open(path, 'rb') as csvfile:

Using 'rb' is entirely correct, the csv module recommends you do so:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Windows is such a platform.

like image 101
Martijn Pieters Avatar answered Oct 02 '22 19:10

Martijn Pieters