我读一个CSV文件转换成namedtuple像这样:阅读CSV文件小写与Python
import csv
from collections import namedtuple
#So we can handle bad CSV files gracefully
def unfussy_reader(reader):
while True:
try:
yield next(reader.lower())
# This is a bad row that has an error in it (csv.Error)
# Alternately it may be a line that doesn't map to the structure we've been given (TypeError)
except (csv.Error, TypeError):
pass
continue
# Create the CSV reader object
csv_reader = csv.reader(file_stream, delimiter=' ', quotechar='"', escapechar='^')
# Set up the named tuple
csvline = namedtuple('csv_line', 'field1, field2, field3')
# Create the named tuple mapping object
map_to_tuple = map(csvline._make, csv_reader)
for line in unfussy_reader(map_to_tuple):
# do stuff
这个效果很好,但我的问题是 - 我希望所有的内容CSV以小写字母读取。根据this question,一个简单的lambda会做到这一点: map(lambda x:x.lower(),["A","B","C"])
但我找不到任何地方把它放在数据结束在元组(因此无法分开)之前。
在这个结构(Python 3.5)中有没有办法做到这一点?
在'csv_reader = ...'之前添加一行:'file_stream =(line.lower()for file in file_stream)'? – bbayles
@bbayles - 工作,虽然我不得不将它分配给某些东西,然后改变'csv_reader ='行来指向,而不是'file_stream'。发布它作为答案,我会接受。谢谢 –