python - 尝试打印 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”。我以前使用过这段代码并且它有效。有什么帮助吗?谢谢!
解决方案
欢迎来到 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
推荐阅读
- c++ - 在 C++ 中模板化列表
- python - 特定元素的 Python/Flask 解析响应
- java - 如何使用带有按钮和字符串值的 JSON API 数据
- sql - 如何使用 SQL 连接两个表以获取运动员姓名
- c++ - 模 10^9+7 对现实世界的问题有用吗?
- r - 使用过滤器的最小值或最大值
- javascript - 从数组中选择后反应无法选择多个复选框
- javascript - 嵌套循环,验证是继续循环还是开始下一次迭代
- macos - **错误消息/Users/yyyyyy/.zshenv:.:1: 没有这样的文件或目录:/Users/yyyyyy/.cargo/env**
- android - 如何在 Android 中获取 G-Force Sensor?