no mind about result of csv.DictReader, so and no possibility to know, are csv params specified correctly.
i have input
Device tps kB_read/s kB_wrtn/s kB_dscd/s kB_read kB_wrtn kB_dscd
sda 0.17 53.98 0.14 0.00 55111129 145632 0
sde 0.14 53.99 0.14 0.00 55118669 147152 0
sdg 0.17 53.99 0.14 0.00 55117853 147076 0
only just spaces are trimmed to one
and that way i want to load it
ios_e = csv.DictReader(' '.join(ios_r.stdout.split()), delimiter = ' ', fieldnames = {'Device', 'tps', 'kB_read/s' ,'kB_wrtn/s', 'kB_dscd/s', 'kB_read', 'kB_wrtn', 'kB_dscd'})
*without specifying fieldnames result is worse, but it should be got by first line? but not
and, for example, I want to work with my Dict:
for v in ios_e.reader:
for d in v:
print(d)
and have (there more)
D
e
v
i
c
e
t
p
what i did - you see, what i am shold expect - i don't now I expected matrix-like object, becouse csv like it
what i am get and why?
CodePudding user response:
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']
.
CodePudding user response:
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.