简体   繁体   English

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

[英]Python - Printing a CSV file into the console as a table

I have been trying to print a csv file into the console in such way that it is structured like a table. 我一直试图将csv文件打印到控制台中,使其结构像表一样。

--> Desiered output: ->所需的输出:

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

But instead with the next methods I have tried I have been unable to get it. 但是相反,我尝试使用下一种方法无法获得它。

--> CSV File -> 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

--> Method 1: ->方法一:

import csv

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

--> Output of Method 1: ->方法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"]

Method 1 prints me all the values correctly but I didnt find any way so it gets printed like my desire output. 方法1正确地打印了我所有的值,但是我没有找到任何方法,因此像我期望的输出一样被打印。

--> Method 2: ->方法2:

import pandas as pd

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

--> Output of Method 2: ->方法2的输出:

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

Because of the length of the values Im using and the number of fields I have, part of the columns are getting cutten out, only leaving me with part of the information. 由于Im使用的值的长度和我拥有的字段数,部分列被删去了,只留下了部分信息。 ( Maybe it works for the table I have showed here, but in my case Fields AE may have up to 20 characteres each ) (也许它适用于我在此处显示的表格,但在我的情况下,字段AE最多可以包含20个字符)

I have not encountered any other method which would work to give me the first value, method 1 and 2 being the ones I mostly tried to use to get my desired output. 我还没有遇到其他任何可以给我第一个值的方法,方法1和2是我通常试图用来获取所需输出的方法。

Thanks. 谢谢。

Given your desired formatting, using Pandas would be your best bet. 给定您想要的格式,使用Pandas将是您的最佳选择。 To get around the ellipses for columns, you can change the display.max_columns option for Pandas. 要绕过列的省略号,可以更改Pandas的display.max_columns选项。

Example: 例:

import pandas as pd

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

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

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

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

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