Write to file, replace words / numbers

1

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

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

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)
    
asked by anonymous 20.03.2015 / 09:10

1 answer

0

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")
    
20.03.2015 / 14:27