2

I have been trying to print a csv file into the console in such way that it is structured like a table.

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

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:

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

--> Method 2:

import pandas as pd

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

--> Output of Method 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. ( Maybe it works for the table I have showed here, but in my case Fields A-E may have up to 20 characteres each )

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.

Thanks.

PSM
  • 429
  • 4
  • 15

2 Answers2

2

Given your desired formatting, using Pandas would be your best bet. To get around the ellipses for columns, you can change the display.max_columns option for Pandas.

Example:

import pandas as pd

file = "file.csv"
df = pd.read_csv(file)
pd.options.display.max_columns = len(df.columns)
print(df)
Henry Woody
  • 14,024
  • 7
  • 39
  • 56
0

In pandas you can configure the maximum string length using the max_colwidth option:

pd.set_option("display.max_colwidth", 10000) have
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • That doesnt seem to work for me, I imagine that it is another way of expresing pd.options.display.max_columns which Henry said, thanks anyway. – PSM Oct 23 '18 at 18:26