我正在将我编写的 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>"
最佳答案
使用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()
驱动的字符串中使用命名槽模板。
关于python - python 中制表符分隔文件的 `while read ... do; ... done < file` 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704359/