Python csv.DictReader - Stack Overflow
Python csv.DictReader: parse string? - Stack Overflow
csv.DictReader
python - understanding csv DictReader, what it returns? - Stack Overflow
» pip install openpyxl-dictreader
I found this gem while reading the book, Practical Python Design Patterns. It reads a csv file and transforms each row into a dictionary with column names being the keys, and row contents being the values. Check it out: csv.DictReader. There is a complementary csv.DictWriter as well.
The csv.DictReader function expects a file object as its first argument, not a string. So, it always is used with normal file io.
for example,
with open('input.csv', 'r') as f:
reader = csv.DictReader(f, delimiter=' ', fieldnames = ['Device', 'tps', 'kB_read/s' ,'kB_wrtn/s', 'kB_dscd/s', 'kB_read', 'kB_wrtn', 'kB_dscd'])
And, you can iterate the reader (i.e., iterable of dicts) row by row.
for row in reader:
print(row)
The row variable contains dictionary-like object that you can easily access by key, for example, row['Device'].
The csv module expects the input to be an iterable containing lines of the CSV. ' '.join(ios_r.stdout.split()) is returning a single string (it simply collapses all the whitespace delimiters into single spaces). Iterating over a string returns loops over the characters, not the lines.
You should perform the join and split on each line, not the entire stdout at once.
ios_e = csv.DictReader(' '.join(line.split()) for line in ios_r.stdout, delimiter = ' ')
You won't need the fieldnames argument in this code, since it will get them from the first line.