简体   繁体   English

csv 文件的内容以表格形式打印

[英]Content of csv file to printed in tabular form

I want the content of csv file to printed in tabular form.我希望以表格形式打印 csv 文件的内容。

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

But whenever I try to run this code the content gets shuffled like if I have但是每当我尝试运行此代码时,内容就会像我有

name  class  section
a      xi     A

instead of this it becomes而不是这个,它变成

name  class    section
a      xi   A

the "A" is not in proper column “A”不在正确的列中

To ensure each of your columns has the correct width, you would need to first read all of your data in before printing.为确保您的每一列都具有正确的宽度,您需要在打印之前先读取所有数据。 You can then determine the maximum width of each column and then print it.然后,您可以确定每列的最大宽度,然后打印它。 For example:例如:

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)

Giving you:给你:

name  class  section
a     xi     A

widths is a list holding the maximum width needed for each columns. widths是一个列表,其中包含每列所需的最大宽度。 The f string here is gives each value the correct width padding.这里的f字符串为每个值提供了正确的宽度填充。 It then adds a col_spacer between each column.然后它在每列之间添加一个col_spacer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM