You have a problem when you use the i.replace(...)
this doesn’t really remove line breaks because strings in Python are immutable, what you want to do is:
i = i.replace("\n", "")
Since you did not mention more details about what you want to remove, I will assume that they are not decimal numbers, but integers, for this you can use the method isdigit()
to check whether the current line contains numbers or not.
Follow 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 in Ideone.
In Python 3 equals:
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 in Ideone.
The fileinput
is an auxiliary module in the handling of files, the inplace
when used with the value True
, causes the standard output (stdout) is directed to the input file.
If you need to work with decimal numbers and need 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 in Ideone.
Another simpler way that uses the 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")
What you got wrong in what you want?
– Maniero
Simply does not do what I want, does not give error but also does not remove the numbers
– Miguel
You have to say what you want or at least give details of the problem. It seems to me that you do what you want but I may not have understood.
– Maniero