首页 > 解决方案 > 尝试打印 csv 文件时出现新的 python NameError

问题描述

我的代码以前可以打印到 csv 文件,但最近开始产生 NameError。我已经查看了许多其他类似的问题,但无法弄清楚如何解决它。我对 Python 比较陌生。

data = glob.glob('filename****')
filenames = data

for filename in filenames:
  root = lxml.etree.parse(filename)
  for stitle in root.xpath("//fileDesc/titleStmt/title[1]"):
      stitle = stitle.xpath("string()")

  for ltitle in root.xpath("//fileDesc/titleStmt/title[2]"):
      ltitle = ltitle.xpath("string()")

  for date in root.xpath("//fileDesc/sourceDesc/bibl/msDesc/additional/adminInfo/note"):
      date = date.xpath("string()")

  for location in root.xpath("//fileDesc/sourceDesc/bibl/pubPlace"):
      location = location.xpath("string()")

  with open('file.csv', 'a') as csv_file:
      writer = csv.writer(csv_file)
      writer.writerow([filename, stitle, ltitle, date, location])

我收到的具体错误是“NameError: name 'date' is not defined”。我以前使用过这段代码并且它有效。有什么帮助吗?谢谢!

标签: pythonexport-to-csvnameerror

解决方案


欢迎来到 StackOverflow。

我猜你是第一次使用 root.xpath("//fileDesc/sourceDesc/bibl/msDesc/additional/adminInfo/note")空值运行程序。

在这种情况下,名称date永远不会被绑定,因此当您尝试执行最终语句时

writer.writerow([filename, stitle, ltitle, date, location])

你会看到一个 NameError。本次互动环节将展示:

>>> for date in []:
...   pass
...
>>> date
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'date' is not defined

推荐阅读