Format output in txt file

Asked

Viewed 178 times

1

I have the following code:

def verificaPrimo(num):
    if int(num) < 2:
        return False
    else:
        for n in range(2, int(num)):
            if int(num) % int(n) == 0:
                return False
        return True


def obtemNumeros(nomeArquivo):
    arquivo = open(nomeArquivo, "r")
    linha = arquivo.readline()
    numeros  = linha.split()
    for line in arquivo:
        numeros += line.split()
    arquivo.close()
    return numeros


arq = open("resultPrimos.txt", "w")
nomeArquivo = "numeros.txt"
numeros = obtemNumeros(nomeArquivo)
for numero in numeros:
    verificaPrimo(numero)
    if verificaPrimo(numero) == True:
        arq.write(numero)
        arq.write("\n")
arq.close()

The checks are OK, generate the output file is OK too, write the prime numbers in that file is OK too.

My problem is this:

In my input file, which is the.txt file, its content is:

1 2 3 4 5 6 7 8 9 10
50 -13 13 11
1
2
3

The output I get in the resultPrimos.txt file is:

2
3
5
7
13
11
2
3

I need the exit to be as follows:

2 3 5 7
13 11

2
3

Could you help me?

Note: yes, on the line where there are no primes, you must print a blank line.

2 answers

3

You can write in exactly the same line where you found these cousins.

Suggesting another way to do but getting the expected result:

def verificaPrimo(num): 
    return all(num%i!=0 for i in range(2,num)) and num > 1 # se o modulo de todos os num ate este for diferente de 0 e maior que 1

def obtemNumeros(nomeArquivo):
    with open(nomeArquivo, "r") as f:
      for l in f:
        yield l.split()

nomeArquivo = "numeros.txt"
txt_write = ''
for nums in obtemNumeros(nomeArquivo):
    txt_write += '{}\n'.format(' '.join([i for i in nums if verificaPrimo(int(i))])) # filtrar os primos e contruir o texto desta linha 
print(txt_write.strip(), file=open("resultPrimos.txt", 'w')) # escrever no ficheiro e remover ultima quebra de linha com o strip()

Output:

2 3 5 7
13 11

2
3

With this approach we are building the text to write in resultPrimos.txt at the same time as we go through the archive we are reading (numeros.txt).

DEMONSTRATION

Not for this particular problem, but I recommend you see this publication: How to generate 200,000 primes as fast as possible in Python?

2


Santana, since you want to keep the data on the respective lines, I thought using a list of vectors would be an alternative:

def verificaPrimo(num):
  if int(num) < 2:
    return False
  else:
    for n in range(2, int(num)):
      if int(num) % int(n) == 0:
        return False
    return True


def obtemNumeros(nomeArquivo):
  arquivo = open(nomeArquivo, "r")
  numeros = []
  for line in arquivo:
    numeros.append(line.replace("\n", "").split(" "))
  arquivo.close()
  return numeros


arq = open("resultPrimos.txt", "w")
nomeArquivo = "numeros.txt"
numeros = obtemNumeros(nomeArquivo)
for linha in numeros:
  primos = ""
  for numero in linha:
    if verificaPrimo(numero):
      primos += numero + " "

  arq.write(primos + "\n")
arq.close()

Thus, each position of the list, is a line that contains the numbers that will be evaluated and written, as a condition, so always a line will be written in the file, even if blank.

But with that, I had to create two loops, one for the list and one for your content.

Browser other questions tagged

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