【问题标题】:Python - Printing a CSV file into the console as a tablePython - 将 CSV 文件作为表格打印到控制台中
【发布时间】:2018-10-23 18:15:49
【问题描述】:

我一直在尝试将 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)

--> 方法一的输出:

["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)

--> 方法二的输出:

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

由于我使用的值的长度和我拥有的字段数量,部分列被删除,只留下部分信息。 (也许它适用于我在这里展示的表格,但在我的情况下,字段 A-E 可能每个最多 20 个字符)

我还没有遇到任何其他可以为我提供第一个值的方法,方法 1 和 2 是我最常尝试使用的方法来获得所需的输出。

谢谢。

【问题讨论】:

  • 方法一:print('\t'.join(row))工作?
  • @roganjosh 差不多,去掉了 [] 但间距不正确,所以标题和值不在相位

标签: python python-3.x pandas csv printing


【解决方案1】:

鉴于您想要的格式,使用 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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这似乎对我不起作用,我想这是亨利说的另一种表达 pd.options.display.max_columns 的方式,无论如何谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 2022-01-13
    • 2021-08-26
    • 1970-01-01
    • 2017-03-18
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多