使用Python以小写形式读取CSV文件

时间:2016-01-03 16:29:54

标签: python csv python-3.x map-function

我正在将CSV文件读入一个namedtuple,如下所示:

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的所有内容。根据{{​​3}},一个简单的lambda会这样做: map(lambda x:x.lower(),["A","B","C"]) 但是在数据最终出现在元组中之前我无法找到任何地方(因而无法使用)。

有没有办法在这个结构中做到这一点(Python 3.5)?

2 个答案:

答案 0 :(得分:3)

您可以在为其创建CSV阅读器之前将lower转换应用于流。

lower_stream = (line.lower() for line in file_stream)
csv_reader = csv.reader(lower_stream, delimiter=' ', quotechar='"', escapechar='^')

lower_stream分配目标周围的括号指定generator expression。它不会用完file_stream并且不会将所有file_stream拉入内存。

答案 1 :(得分:0)

这个怎么样:

csv_reader = csv.reader(map(lambda line:line.lower(),file_stream), delimiter=' ', quotechar='"', escapechar='^')