Whats the python equivalent of a `while read ... do; ... done < file` for tab delimited file? -


i'm in process of converting bash scripts i've written python (my bash chops put me in minority i'm working).

i've got bash while read function loop opens file , formats tab delimited content html table:

function table_item_row {     old_ifs="${ifs}"     ifs=$'\t'     while read code price description link picture line;         printf "    <tr>\n"         printf "      <td><img src=\"%s\"></td>\n" "${picture}"         printf "      <td><a href=\"%s\">%s</a> ($%.2f)</td>\n" "${link}" "${description}" "${price}"         printf "    </tr>\n"     done < inventory.txt     ifs="${old_ifs}" } 

i can in python, but, having heard of csv module, i'm wondering if there's preferred way:

for line in open(filename):     category, code, price, description, link, picture, plans = line.split("\t")     print "    <tr>"     print "      <td><img src=\"" + picture + "\"></td>"     print "      <td><a href=\""+ link + "\">" + description + "</a> ($%.2f)</td>" % float(price)     print "    </tr>" 

use csv module , string formatting:

import csv  fields = ('category', 'code', 'price', 'description', 'link', 'picture', 'plans') table_row = '''\     <tr>       <td><img src="{picture}"></td>       <td><a href="{link}">{description}</a> ({price:.2f})</td>    </tr> '''  open(filename, 'rb') infile:     reader = csv.dictreader(infile, fieldnames=fields, delimiter='\t')     row in reader:         row['price'] = float(row['price'])  # needed make `.2f` formatting work         print table_row.format(**row) 

the csv.dictreader() class turns rows dictionaries, handier here because can use named slots in str.format()-powered string template.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -