Write to file, replace words/numbers

Asked

Viewed 1,714 times

1

I have this code that is supposed to read a file and delete all the numbers that are there, the file is like a list of words, Ex: "Ana n Bruno n 123 n 10 n ...".

A line has letters or numbers, never the two mixed.

What I want is to remove the numbers, my code so far:

foo = open("words.txt", "r+w")

for i in foo:
   i.replace("\n", "")
   try:
      int(i)
   except:
      word = i+ "\n"
      foo.write(word)
  • What you got wrong in what you want?

  • Simply does not do what I want, does not give error but also does not remove the numbers

  • 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.

1 answer

0


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")

Browser other questions tagged

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