我一直在尝试将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是我大多数时候试图用来得到我想要的输出的方法。
谢谢.
3条答案
按热度按时间p1tboqfb1#
考虑到你想要的格式,使用Pandas将是你最好的选择。要绕过列的省略号,你可以更改Pandas的
display.max_columns
选项。范例:
字符串
wkftcu5l2#
我建议您考虑将
tabulate
与pandas
结合使用。我一直在尝试将csv文件打印到控制台中,使其结构类似于表格。
如果您的主要目标是控制输出的性质,通过使用
tabulate
,您将能够指定许多表示细节,例如边框的存在,标题和索引的文本对齐显示。示例
使用应用于示例csv的
heavy_grid
生成表格输出。字符串
输出
型
hivapdat3#
在pandas中,您可以使用max_colwidth选项配置最大字符串长度:
字符串