Python -将CSV文件作为表打印到控制台

gopyfrb3  于 11个月前  发布在  Python
关注(0)|答案(3)|浏览(138)

我一直在尝试将csv文件打印到控制台中,使其结构类似于表格。
-->所需输出:

Key   Field_1   Field_2   Field_3   Field_4
A0    B0        C0        D0        E0
A1    B1        C1        D1        E1
A2    B2        C2        D2        E2

字符串
但是,相反,我已经尝试了接下来的方法,我一直无法得到它。
--> CSV文件

Key,Field_1,Field_2,Field_3,Field_4
A0,B0,C0,D0,E0
A1,B1,C1,D1,E1
A2,B2,C2,D2,E2


-->方法一:

import csv

file = "file.csv"
opened = open(file, "r")
readed = csv.reader(opened, delimiter=",")
for row in readed:
    print(row)


-->方法1的输出:

["Key", "Field_1", "Field_2", "Field_3", "Field_4"]
["A0", "B0", "C0", "D0", "E0"]
["A1", "B1", "C1", "D1", "E1"]
["A2", "B2", "C2", "D2", "E2"]


方法1正确地打印了我所有的值,但我没有找到任何方法,所以它得到了像我的愿望输出打印。
-->方法二:

import pandas as pd

file = "file.csv"
opened = open(file, "r")
readed = pd.read_csv(file)
print(readed)


-->方法2的输出:

Key   Field_1   ...   Field_4
A0    B0        ...        E0
A1    B1        ...        E1
A2    B2        ...        E2


由于我使用的值的长度和我拥有的字段的数量,部分列被剪切掉了,只给我留下了部分信息。(也许这对我在这里展示的表是有效的,但在我的例子中,字段A-E可能每个字段最多有20个字符)
我还没有遇到过任何其他方法可以给予我第一个值,方法1和2是我大多数时候试图用来得到我想要的输出的方法。
谢谢.

p1tboqfb

p1tboqfb1#

考虑到你想要的格式,使用Pandas将是你最好的选择。要绕过列的省略号,你可以更改Pandas的display.max_columns选项。
范例:

import pandas as pd

file = "file.csv"
df = pd.read_csv(file)
pd.options.display.max_columns = len(df.columns)
print(df)

字符串

wkftcu5l

wkftcu5l2#

我建议您考虑将tabulatepandas结合使用。
我一直在尝试将csv文件打印到控制台中,使其结构类似于表格。
如果您的主要目标是控制输出的性质,通过使用tabulate,您将能够指定许多表示细节,例如边框的存在,标题和索引的文本对齐显示。

示例

使用应用于示例csv的heavy_grid生成表格输出。

from tabulate import tabulate
import pandas as pd
print(tabulate(pd.read_csv("grad-adm.csv", nrows=5), 
               headers="keys", tablefmt="heavy_grid"))

字符串

输出

┏━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━┓
┃    ┃   columnA ┃   columnB ┃   OtherColumn ┃   rank ┃
┣━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━━━━╋━━━━━━━━┫
┃  0 ┃         0 ┃        10 ┃          3.61 ┃      3 ┃
┣━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━━━━╋━━━━━━━━┫
┃  1 ┃         1 ┃        20 ┃          3.67 ┃      3 ┃
┣━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━━━━╋━━━━━━━━┫
┃  2 ┃         1 ┃        30 ┃          4    ┃      1 ┃
┣━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━━━━╋━━━━━━━━┫
┃  3 ┃         1 ┃        40 ┃          3.19 ┃      4 ┃
┣━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━━━━╋━━━━━━━━┫
┃  4 ┃         0 ┃        50 ┃          2.93 ┃      4 ┃
┗━━━━┻━━━━━━━━━━━┻━━━━━━━━━━━┻━━━━━━━━━━━━━━━┻━━━━━━━━┛

hivapdat

hivapdat3#

在pandas中,您可以使用max_colwidth选项配置最大字符串长度:

pd.set_option("display.max_colwidth", 10000) have

字符串

相关问题