尝试从python编程中读取csv文件

时间:2015-04-02 06:44:29

标签: python csv

我将csv文件保存在D目录中并尝试使用python编程读取该csv文件。 这是我在python中的代码:

import csv

try:
     path = "D:\\abc.csv"
     with open("path", "rb") as csvfile:
         readCSV = csv.reader(csvfile, delimiter=',')
         for row in readCSV:
             print (row)    
except Exception, e:
    raise e

这是我得到的错误:

The current working directory is F:\
Traceback (most recent call last):
  File "F:\directory.py", line 16, in <module>
    raise e
IOError: [Errno 2] No such file or directory: 'path'

3 个答案:

答案 0 :(得分:1)

您需要删除path周围的双引号。 &#34;路径&#34;是一个字符串,为了获得path变量的值,你需要按原样放置变量,以便扩展它。

with open(path, "rb") as csvfile:

答案 1 :(得分:1)

删除路径周围的双引号。将其编辑为:

with open(path, "rb") as csvfile:

答案 2 :(得分:1)

这一行

with open("path", "rb") as csvfile: 

应该是

with open(path, "rb") as csvfile:

正如&#34;&#34;中的任何文字或者&#39;&#39;在python中将被视为字符串类型而不是变量。