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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -