【问题标题】:Header for list [duplicate]列表标题[重复]
【发布时间】:2017-03-20 04:06:27
【问题描述】:

这是我文件的开头:

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 文件是:

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

我希望它能够为每个项目添加一个标题。对于开头的数字,我希望它有“GTIN”,然后是“描述”,然后是“价格”,我希望它们符合要求。谢谢

我希望它看起来像

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

这是一个示例,但没有所有循环 http://pastebin.com/7GepdJSu

【问题讨论】:

  • 请提供所需输出的示例。
  • 所以您基本上希望products 成为dict 而不是list
  • 您最后的print 行需要缩进。
  • 如果你没有使用the csv module,那么你就没有解析 CSV。请使用该模块。至于你的问题:你想使用 CSV 文件中的标题吗?还是直接忽略?
  • print('GTIN {} Description {} Price £{}'.format(item[0],item[1],item[2])) ?

标签: python


【解决方案1】:

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

GTIN、描述、价格

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

【讨论】:

  • 我的 csv 文件中没有标题行。我想在 python 中使用它。我也不希望破折号在那里
  • 希望它看起来像这样,如果它有帮助的话。 pastebin.com/7GepdJSu
  • 但没有所有的循环
  • @EbrahimMohammed 我已根据您的 pastebin 格式更新了答案。请阅读我提到的链接并根据要求进行更改。
  • 谢谢,现在知道了。我是新手,但现在有办法删除整个问题吗?感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 2011-12-25
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多