【问题标题】:Content of csv file to printed in tabular form以表格形式打印的 csv 文件内容
【发布时间】:2021-05-19 06:25:07
【问题描述】:

我希望以表格形式打印 csv 文件的内容。

with open ("trial.csv","r") as f1:
csv_r=csv.reader(f1)
for i in csv_r:
    print("\t\t".join(i))

但每当我尝试运行此代码时,内容就会像我有一样被打乱

name  class  section
a      xi     A

它变成了

name  class    section
a      xi   A

“A”不在正确的列中

【问题讨论】:

  • 你有什么特别的理由不使用 pandas 吗?

标签: python csv file


【解决方案1】:

为确保您的每一列都具有正确的宽度,您需要在打印前先读取所有数据。然后,您可以确定每列的最大宽度,然后打印它。例如:

import csv

def print_cols(data):
    col_spacer = "  "       # added between columns
    widths = [max(len(str(item)) for item in row) for row in zip(*data)]
    print('\n'.join(col_spacer.join(f"{col:{widths[index]}}" for index, col in enumerate(row)) for row in data))

with open("trial.csv") as f1:
    csv_r = csv.reader(f1)
    data = list(csv_r)

print_cols(data)

给你:

name  class  section
a     xi     A

widths 是一个列表,其中包含每列所需的最大宽度。这里的f 字符串为每个值提供了正确的宽度填充。然后在每列之间添加一个col_spacer。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2022-01-04
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多