You have a problem, when you use i.replace(...)
this does not actually remove line breaks, because strings in #, what you want to do is:
i = i.replace("\n", "")
As you did not mention more details about what you want to remove, I will assume that they are not decimal numbers, but integers, so you can use isdigit()
to check if the current line contains numbers or not.
Here's an implementation with the module fileinput
:
import fileinput
for linha in fileinput.input("words.txt", inplace=True):
linha = linha.replace("\n", "")
if not linha.isdigit():
print linha
See example on Ideone .
In Python 3 it's equivalent:
import fileinput
for linha in fileinput.input("words.txt", inplace=True):
linha = linha.rstrip("\n") # outro modo de retirar a quebra de linha
if not linha.isdigit():
print (linha, end = "\n")
See example on Ideone .
fileinput
is an auxiliary module in file manipulation, inplace
when used with the value True
, causes the default output ( stdout ) is directed to the input file.
If you need to work with decimal numbers and need to make a copy of the original file, you can do:
import fileinput
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
for linha in fileinput.input("words.txt", backup= ".bak",inplace=True):
linha = linha.rstrip("\n")
if not is_number(linha):
print linha
See example on Ideone .
Another simpler way that uses open
and isdigit()
:
with open('words.txt', 'r+') as f:
linhas = f.readlines()
f.truncate(0) # elimina o conteúdo do arquivo
for linha in linhas:
linha = linha.rstrip("\n")
if not linha.isdigit():
f.write(linha + "\n")