列表的标题

2024-10-04 01:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我文件的开头:

print("Welcome to Ebs Corp.")
print('Please browse my shopping list\n')
with open('./Catalouge2.csv', 'r') as ebsfile:
    products = []
    for line in ebsfile:
        products.append(line.strip().split(','))
    for item in products:
    print('{} {} £{}'.format(item[0],item[1],item[2]))

我的csv文件是:

^{pr2}$

我希望它能够为每个项目添加一个标题。对于一开始的数字,我希望它有'GTIN',然后是'Description',然后是'Price',我希望他们是一致的。谢谢

我希望它看起来像

GTIN---------------Description-----------------Price
12345678-----------Blue-Eyes White Dragon------5.60
87654321-----------Dark Magician---------------3.20

下面是一个例子,但是没有所有的循环http://pastebin.com/7GepdJSu


Tags: 文件csvtoinforlinedescriptionitem
1条回答
网友
1楼 · 发布于 2024-10-04 01:27:41

您应该使用^{} module。您需要的格式可以使用内置的string formatting实现。我假设csv中有一个标题行,如下所示

GTIN,description,price

>>> import csv
>>> print_format = '| {0: <10} | {1: <30} | {2: >5} |'
>>> with open('/home/ashish/Desktop/sample.csv') as csvfile:
...     reader = csv.reader(csvfile)
...     print(print_format.format('GTIN', 'Description', 'Price'))
...     for row in reader:
...         print(print_format.format(row[0], row[1], row[2]))
... 
| GTIN       | Description                    | Price |
| GTIN       | description                    | price |
| 12345678   | Blue-Eyes White Dragon         |  5.60 |
| 87654321   | Dark Magician                  |  3.20 |
| 24681012   | Toon Blue-Eyes White Dragon    |  2.00 |
| 10357911   | Toon Dark Magician             |  3.00 |
| 54626786   | Duel Mat                       |  4.30 |
| 85395634   | Deck Box                       |  2.50 |
| 78563412   | Pot of Greed                   | 10.50 |

相关问题 更多 >