Ignoring a line from a txt file

Asked

Viewed 405 times

0

I read a file . txt where I want to separate each word by comma, ie when finding a space before the word and after.

But I also need to ignore the entire txt line where the ##character is. Below follows the code I was using to separate in comma:

def LeArquivo(arquivo):
linhas = arquivo.readlines()

texto = []

for line in linhas:
    line = line.strip().split(' ')
    texto.append(line)

return texto

Here’s the code I was trying to use to remove the ##

def LeArquivo(arquivo):
linhas = arquivo.readlines()

texto = []

for line in linhas:
    line = line.strip().split(' ')
    if line.find('##') != 0:
        texto.append(line)

return texto

But an error occurs when executing: Attributeerror: 'list' Object has no attribute 'find'

2 answers

2


Issue of order of commands, you are transforming the string read in a list and then comparing but as the lists do not have the method .find() you get an error message.

Based on your function a step by step version...

def le_arquivo(nome_do_arquivo):
    # 1. cria a lista
    texto = []
    # 2. Abre o arquivo para leitura
    with open(nome_do_arquivo, "r") as arquivo:
        # 3. Lê cada linha do arquivo por vez
        for linha in arquivo:
            # 4. Os dois primeiros caracteres não são "##"?
            if linha[0:2] != "##":
                # 5. Então quebre a string e adicione à lista
                texto += [linha.strip().split(" ")]
    # 6. Devolve a lista
    return texto

Another thing you could even replace the line.find('##') != 0 for '##' not in line but you would be unnecessarily suing a string then it becomes more efficient for you to validate the case and then process.

  • 1

    The condition could also be if(not linha.startswith('##')):.... Good answer/explanation

  • cool! was unaware of the "##" not in str

  • Thanks for the help @Giovanni, it worked perfectly here! With your tips I even managed to make other parts of the code I needed. Vlw!

0

Already now a more compact version of the (and less readable) version of the @Giovanni reply (I’m a bit addicted to lists by understanding)

def le(nome):
    with open(nome, "r") as arquivo:
        return[ l.split() for l in arquivo if "##" not in l ]
    return []

print(le("exemplo.txt"))

Browser other questions tagged

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