什么是蟒蛇相当于`读取...做; ......完成<文件`用于制表符分隔文件?

时间:2013-07-17 15:44:54

标签: python python-2.7

我正在将我编写的BASH脚本转换为python(我的BASH印章让我处于少数我正在工作的地方)。

我有一个BASH while read函数循环,用于打开文件并将制表符分隔的内容格式化为HTML表格:

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}"
}

我可以在python中做这样的事情,但是,听说过csv模块,我想知道是否有一种首选方式:

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

2 个答案:

答案 0 :(得分:3)

使用csv modulestring 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>
'''

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()驱动的字符串模板中使用命名的插槽。

答案 1 :(得分: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