Reading in csv file and converting to python in uppercase

综合编程 2018-04-22 阅读原文

I'm trying to read in a csv file using the csv library. I'm attempting to iterate through each line but convert to upper case before I attempt some useful function with each line.

import csv
reader = csv.DictReader(open('sample.csv', 'rb'))
for line in reader:
    line = line.upper()
    name = line['Name']

The above code doesn't appear to work. It fails when I attempt to convert the line read in to upper. I can change each column of the csv file read in to upper individually (using dictionary key) but I want to avoid that since there are lots of keys in the dictionary.

You can pre-process each line from the file object using a generator expression, before passing them to csv.DictReader
which returns an iterable of dicts:

with open('sample.csv', 'rb') as f:
    header = next(f).strip().split(',')
    reader = csv.DictReader((l.upper() for l in f), fieldnames=header)
    for line in reader:
        name = line['Name']

Demo:

>>> f = ['a,b', 'c,d']
>>> c = csv.DictReader((l.upper() for l in f), fieldnames=('h1', 'h2'))
>>> list(c)
[{'h2': 'B', 'h1': 'A'}, {'h2': 'D', 'h1': 'C'}]
Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!

您可能感兴趣的

使用 web3.py 实现 ERC20 Token 空投 随着一些交易所搞的上币排名的活动开展,也带来了空投的火爆,当然也给以太坊整个网络带来了很大的考验(极其拥堵、交易费水涨船高),本篇文章还是从技术上来看看实现空投的一种通用方案。 关于空投的实现需要提前了解一下 ERC20 标准中的下面几...
Package Management in Python – Part I This post was originally published on http://snoozy.ninja/ . Dependency hell - The situation when installed software...
Snapcraft at Europython 2018 In July, several members of our advocacy and design teams went to Europython 2018 in Edinburgh. It was a really well-or...
python 闭包 # python 闭包 # 1.什么是闭包如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用, 那么就构成了闭包(closure)。 def out(x): def inn...
Python : How to Get the current working directory ... In this article we will discuss how to get the current working directory in Python. Python’s os module provides a func...