我讀一個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'。發佈它作爲答案,我會接受。謝謝 –