How to create conditions in read and write text files (python3)?

Asked

Viewed 67 times

0

So how could I pick up a text like this for example:

"testo<br>de<br>exemplo<br>"

and create a conditional (after giving the .open('file.txt', 'r')) for each time the program finds the < br > when reading the file, skip a line (and maybe even delete the < br > after skipping the line)? Thanks in advance.

arquivo = open('arquivo.txt', 'w')

for line in arquivo:
    if #pedaçodaline == '<br':
        # deletar o <br>
        print('\n')

1 answer

1


To make the program "skip" a line when finding the "<br>" in the text, just use the string method replace to replace this element with the special character "\n".

See the example below:

file = open("arquivo.txt", "w")
texto = file.read()

texto = texto.replace("<br>", "\n") # Substitui o "<br>" pelo caractere de quebra de linha

To delete this element from the text, just use the same method only now passing an empty string in the second parameter.

texto = texto.replace("<br>", "")

A very interesting thing is that it is not necessary to create a conditional to do this since, if the character exists on the line it will be replaced and if it does not exist, no modification will happen on the line.

Your code would then look like this:

arquivo = open('arquivo.txt', 'w')

for line in arquivo:
    line = line.replace("<br>", "")

    # Seu código...
  • Got it here! Thank you very much!

Browser other questions tagged

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