简体   繁体   中英

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'

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.

您当前的猜测是正确的:要么将文件放在测试代码目录中,要么将python指向正确的路径。

Make a fresh rename of your folder. That worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM