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']


>>> 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!阅读原文】。感谢您的支持!


Import Python: #156: Tensorflow, Machine learning ... Poodle, Pug, or Wiener Dog? Deploy a Dog Identification TensorFlow Model Using ...
python-9-IO编程 1-文件读写 f = open('d:/file.txt','r') #如果文件不存在会报异常 print( #一次性读取所有内容...
对python并发编程的思考 为了提高系统密集型运算的效率,我们常常会使用到多个进程或者是多个线程,python中的 Threading 包实现了线程, multiproces...
Davide Moro: Hello pytest-play! pytest-play is a rec &play (rec not yet available) pytest plugin ...
python获取http代理 主要是从以及获取相关的代理...