【发布时间】:2012-04-29 21:06:17
【问题描述】:
问题
代码没有正确识别输入(项目)。即使 CSV 文件中存在这样的值,它也会简单地转储到我的失败消息中。谁能帮我确定我做错了什么?
背景
我正在开发一个小程序,该程序要求用户输入(此处未给出函数),搜索 CSV 文件(项目)中的特定列并返回整行。 CSV 数据格式如下所示。我已经从实际数量(49 个字段名称,18000+ 行)中缩短了数据。
代码
import csv
from collections import namedtuple
from contextlib import closing
def search():
item = 1000001
raw_data = 'active_sanitized.csv'
failure = 'No matching item could be found with that item code. Please try again.'
check = False
with closing(open(raw_data, newline='')) as open_data:
read_data = csv.DictReader(open_data, delimiter=';')
item_data = namedtuple('item_data', read_data.fieldnames)
while check == False:
for row in map(item_data._make, read_data):
if row.Item == item:
return row
else:
return failure
CSV 结构
active_sanitized.csv
Item;Name;Cost;Qty;Price;Description
1000001;Name here:1;1001;1;11;Item description here:1
1000002;Name here:2;1002;2;22;Item description here:2
1000003;Name here:3;1003;3;33;Item description here:3
1000004;Name here:4;1004;4;44;Item description here:4
1000005;Name here:5;1005;5;55;Item description here:5
1000006;Name here:6;1006;6;66;Item description here:6
1000007;Name here:7;1007;7;77;Item description here:7
1000008;Name here:8;1008;8;88;Item description here:8
1000009;Name here:9;1009;9;99;Item description here:9
备注
我在 Python 方面的经验相对较少,但我认为这将是一个很好的问题,以便了解更多信息。
我确定了打开 CSV 文件(并在关闭函数中包装)的方法,通过 DictReader 读取数据(以获取字段名称),然后创建一个命名元组以便能够快速选择所需的列输出(项目、成本、价格、名称)。列顺序很重要,因此使用 DictReader 和 namedtuple。
虽然有可能对每个字段名称进行硬编码,但我觉得如果程序可以在打开文件时读取它们,那么在处理具有相同列名称但不同的类似文件时会更有帮助列组织。
研究
- CSV 标头和命名元组: What is the pythonic way to read CSV file data as rows of namedtuples?
- 将 CSV 数据转换为元组:How to split a CSV row so row[0] is the name and any remaining items are a tuple?
- 还有其他研究链接,但我不能发布超过两个。
【问题讨论】:
-
你不需要在文件上使用
closing()- 它的上下文管理器默认已经关闭了文件。只需使用with open(...) as file:。 -
while check == False:是什么?永远都是真的…… -
好的。我基于 docs.python.org/py3k/library/… 使用了 close()。我在 open() 的文档中读到它确实关闭了 IO,但我只是觉得它比抱歉更安全,因为我不确定有什么区别。
-
约翰,那是另一个声明的剩余部分。我试图彻底检查代码,但我错过了。过了一会儿,线条开始融合。
-
是的,
closing()用于向尚不支持的对象添加对上下文管理器的支持。正如open()返回的文件对象所做的那样,您可以放心地不使用它(尽管它基本上会产生最终结果)。