当我尝试在 jupyter notebook 中加载 CSV 文件时,为什么会出现名称错误

why do i get a nameerror when i try to load a CSV-File in jupyter notebook

我的 csv 文件具有以下结构:

 ID    fromEmail   ID toEmail
 134     a@a.com   23  b@b.com
 33      aa@a.com  323 bbb@b.com

我的 jupyter notebook 上有以下代码:

 import csv as pt
 with open(dnc-temporalGraph.csv, 'rb') as f:
    data = list(csv.reader(f))

和以下 NameError:

     NameError                            Traceback (most recent call last)
     <ipython-input-65-1b0399e4e4b5> in <module>()
           1 import csv as pt
     ----> 2 with open(dnc-temporalGraph.csv, 'rb') as f:
           3     data = list(csv.reader(f))

     NameError: name 'dnc' is not defined

我已经检查了其他一些问题,例如 this and this,但仍然无法弄清楚我在这里做错了什么。如果我像第二个 link 一样将文件名放在单引号之间,那么我会得到一个 IOError

IOError: [Errno 2] No such file or directory: 'dnc-temporalGraph.csv'

请帮忙?

您需要将文件名作为字符串传递:

with open("dnc-temporalGraph.csv", 'rb') as f:

否则会认为你调用的是变量dnc

确保笔记本与您的 csv 位于同一位置。如果它不在同一位置,则必须提供完整路径:"C:/user/x/file_name.csv"


最后,您将 csv 导入为 pt

删除 as pt 或将条目 "csv.reader(f)" 更改为 "pt.reader(f)"


所以你的代码应该是:

import csv as pt
with open("dnc-temporalGraph.csv", 'rb') as f:
   data = list(pt.reader(f))