Python csv to dictionary with first line as title -
i have file file.csv data:
fn,ln,tel john,doe,023322 jul,dap,024322 jab,sac,0485
i have array can access this:
file = 'file.csv' open(file,'ru') f: reader = csv.dictreader(f) print reader[0].fn
so prints first name first record. unfortunately, error:
valueerror: i/o operation on closed file
how can done don't need keep file opened , can play array. btw, don't need write in csv file, need use data , that, array can modify best.
you need access reader *within with
block, not outside of it:
file = 'file.csv' open(file,'ru') f: reader = csv.dictreader(f) first_row = next(reader) print first_row['fn']
as move code outside block, f
file object closed , cannot obtain rows reader anymore. kind of point of with
statement.
if want have random access rows in file, convert reader list first:
file = 'file.csv' open(file,'ru') f: reader = csv.dictreader(f) all_rows = list(reader) print all_rows[0]['fn']
the list()
call iterate on reader
, adding each result yielded list object until rows read. make sure have enough memory hold rows.
Comments
Post a Comment