1

I'm in the process of converting BASH scripts I've written into python (my BASH chops put me in a minority where I'm working).

I've got a BASH while read function loop that opens a file and formats the tab delimited content into an HTML table:

function table_item_row {
    OLD_IFS="${IFS}"
    IFS=$'\t'
    while read CODE PRICE DESCRIPTION LINK PICTURE LINE; do
        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 do something like this in python, but, having heard of the csv module, I'm wondering if there's a 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>"
4

2 回答 2

3

使用csv模块字符串格式

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>
'''

with open(filename, 'rb') as infile:
    reader = csv.DictReader(infile, fieldnames=fields, delimiter='\t')
    for row in reader:
        row['price'] = float(row['price'])  # needed to make `.2f` formatting work
        print table_row.format(**row)

该类csv.DictReader()将您的行变成字典,在这里更方便,因为您可以在str.format()-powered 字符串模板中使用命名槽。

于 2013-07-17T15:48:49.410 回答
0

您可以使用该csv模块。

>>> import csv
>>> with open(filename) as f:
    for row in csv.reader(f, delimiter='\t'):
        category, code, price, description, link, picture, plans = row
于 2013-07-17T15:48:32.953 回答