Reputation: 49
I'm trying to write a function in python, which reads csv files and returns them nicely formatted. The input files are just standard csv files. Where each line represents a person. The output format should look like:
[
("Age", "Gender", "Weight (kg)", "Height (cm)"),
("28", "Female", "58", "168"),
("33", "Male", "", "188")
]
The thing is just don't know how I can do this. I know that I can loop through every element in my list of lists and print it, but I would like to return them as above. The only format I manage to end up with looks like:
[('Age', 'Gender', 'Weight (kg)', 'Height (cm)'), ('28', 'Female', '58', '168'), ('33', 'Male', '', '188')]
In case anyone need to see my code(I guess it's not nicely coded at all but I'm learning):
def read_csv(path):
newlist = []
with open("example.csv", "r") as f:
nr_of_lines = 0
for line in f.readlines():
counter = 0
nr_of_lines += 1
while "," in line:
idx = line.find(",")
entry = line[0:idx]
newlist.append(entry)
line = line[idx+1:]
counter += 1
if "," not in line:
idx2 = line.find("\n")
newlist.append(line[:idx2])
nr_elements_per_line = int(len(newlist)/nr_of_lines)
tuple_list = []
for i in range(nr_of_lines):
tuple_list.append(tuple(newlist[nr_elements_per_line*i:nr_elements_per_line+i*nr_elements_per_line]))
return tuple_list
print(read_csv("example.csv"))
Upvotes: 2
Views: 955
Reputation: 77337
Python favors single quotes when writing the REPR (representation) of strings. But you can write your own by emitting the string without quotes and wrapping them yourself.
def my_pformat(table):
tupstr = [", ".join(f'"{s}"' for s in tup) for tup in table]
tupline = [f" ({tup})" for tup in tupstr]
return "\n".join(["["] + tupline + ["]"])
table = [('Age', 'Gender', 'Weight (kg)', 'Height (cm)'),
('28', 'Female', '58', '168'),
('33', 'Male', '', '188')]
print(my_pformat(table))
Result
[
("Age", "Gender", "Weight (kg)", "Height (cm)")
("28", "Female", "58", "168")
("33", "Male", "", "188")
]
Upvotes: 1
Reputation: 332
You can use pprint as shown above. There is a pretty nice library called as tabulate that can be used to display tabular data as shown below.
>>> from tabulate import tabulate
>>> data = [('Age', 'Gender', 'Weight (kg)', 'Height (cm)'), ('28', 'Female', '58', '168'), ('33', 'Male', '', '188')]
>>> print(tabulate(data[1:], headers=data[0]))
Age Gender Weight (kg) Height (cm)
----- -------- ------------- -------------
28 Female 58 168
33 Male 188
>>>
Upvotes: 2
Reputation: 51633
You can use the pprint
module for slightly better printing, or print all yourself:
data = [('Age', 'Gender', 'Weight (kg)', 'Height (cm)'),
('28', 'Female', '58', '168'),
('33', 'Male', '', '188')]
print('[')
for inner in data:
print(f"\t{inner}")
print(']')
Output:
[
('Age', 'Gender', 'Weight (kg)', 'Height (cm)')
('28', 'Female', '58', '168')
('33', 'Male', '', '188')
]
With pprint
:
from pprint import pprint
pprint(data)
Output:
[('Age', 'Gender', 'Weight (kg)', 'Height (cm)'),
('28', 'Female', '58', '168'),
('33', 'Male', '', '188')]
Upvotes: 2