-1
I am making a chart using a CSV file through the matplotlib
, but when I print I realize that he gets \n
at the end of each line, the question is how I can resolve?
My code:
import matplotlib.pyplot as plt
def func(a):
lista = []
for i in a:
lista.append(i)
return lista
lst = open(("wealth-per-country.csv"), "r").readlines()
with open("wealth-per-country.csv", "r") as lst:
print(func(lst.readlines()))
How he printa:
['Country,Median_Wealth,Mean_Wealth,Population\n', 'Switzerland,"227,891","564,653","6,866"\n', 'Australia,"181,361","386,058","18,655"\n', 'Iceland,"165,961","380,868",250\n', 'Hong Kong,"146,887","489,258","6,267"\n', 'Luxembourg,"139,789","358,003",461\n', 'Belgium,"117,093","246,135","8,913"\n', 'New Zealand,"116,433","304,124","3,525"\n', 'Japan,"110,408","238,104","104,963"\n', 'Canada,"107,004","294,255","29,136"\n', 'Ireland,"104,842","272,310","3,491"\n', '\n']
Here has several options. As for your code, just do
with open('arquivo') as arq: lista = [ line.rstrip('\n') for line in arq ]
that you already have the list (there is no reason to open the file several times). And its functionfunc
does not make sense, as it receives a list and adds all the elements in another list, without changing anything (you could print direct the return ofreadlines
, because it already returns the list)– hkotsubo
Thanks for the tip!
– MessiTech