1

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.

2
  • Could you post the error information as well? Commented Jul 24, 2017 at 18:22
  • 1
    you use a csv.DictReader object, which returns a dict as you iterate over it instead of a tuple, which is what csv.reader returns. Neither dict nor tuple has an .upper method. You probably want to call .upper on one of the contents of that dict. Commented Jul 24, 2017 at 18:24

2 Answers 2

2

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'}]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use:

import codes
txt = 'sampole.csv'
with codecs.open(txt, 'r', encoding='utf-8') as f:
    lines = f.readlines()
    lines = [x.upper() for x in lines]
lines

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.