尝试打印 csv 文件时的新 python NameError

New python NameError when trying to print csv file

我的代码以前可以打印到 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"。我以前使用过此代码并且它有效。有什么帮助吗?谢谢!

欢迎使用 Whosebug。

我猜你是 运行 第一次使用这样的值的程序 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

这就是你所面对的。
由于 7 不是 gt 9 --> a 未定义。 在您的情况下,未找到 'date'。

if 7 > 9:
    a = 11
print(a)

输出

NameError: name 'a' is not defined