我正在将我编写的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>"
答案 0 :(得分:3)
使用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>
'''
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