简体   繁体   English

在python中读取csv文件时出错“没有这样的文件或目录”

[英]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. 目前我正在尝试使用python中的csv模块读取csv文件。 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. 我的第一个猜测是,我可能将文件保存在错误的位置,或者我需要为pyton提供文件路径。 currently I have the file saved in C:\\Documents and Settings\\eag29278\\My Documents\\python test code\\test_satdata.csv. 目前我将文件保存在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. 一方面注意我注意确定将模式设置为'rb'(读取二进制)是正确的举动。

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. python正在查看当前目录(无论是什么)加载您的文件。 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. 当前目录的内容取决于您如何启动Python脚本以及是否执行了可能已更改当前工作目录的任何代码。

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: 使用'rb'是完全正确的, csv模块建议你这样做:

If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference. 如果csvfile是一个文件对象,则必须在平台上打开“b”标志,这会产生影响。

Windows is such a platform. Windows 就是这样一个平台。

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

Make a fresh rename of your folder. 对文件夹进行重新命名。 That worked for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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