How to remove n while reading lines from a file

Asked

Viewed 65 times

-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']
  • 1

    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 function func 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 of readlines, because it already returns the list)

  • Thanks for the tip!

1 answer

0


Two ways: (There are several)

import matplotlib.pyplot as plt

def func(a: str):
    lista = []
    for i in a:
        lista.append(i.replace('\n', ''))
    return lista

lst = open(("wealth-per-country.csv"), "r").readlines()
with open("wealth-per-country.csv", "r") as lst:
    print(func(lst.readlines()))
    
# OU

def func(a):
    lista = []
    for i in a:
        lista.append(i)
    return [barraN.replace('\n', '') for barraN in lista]

lst = open(("wealth-per-country.csv"), "r").readlines()
with open("wealth-per-country.csv", "r") as lst:
    print(func(lst.readlines()))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.