How to write a lot of values per line in file with Python?

2

I have a code from a physical simulation that I read with MANY INFORMATION and many interactions. For example, I have the qt load calculation, however, there are 100 interactions and I'm working with a qt vector of size 101! I need to save the data from this qt for every interaction I have in a .txt file:

f2.write('%.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f\n'
    %(qt[0],qt[1],qt[2],qt[3],qt[4],qt[5],qt[6],qt[7],qt[8],qt[9],qt[10]))

This is an example of when I have 10 qt's. How would I generalize this so I do not have to write 101 times the '%.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f \t %.20f\n' ?

    
asked by anonymous 16.08.2018 / 15:02

3 answers

6

The action you want to perform is to join, which is given by the method join

16.08.2018 / 15:13
2

You can also use the csv module by manually configuring the delimiter for the \t character %. It would look like:

import csv

with open('arquivo.txt', 'w') as stream:
    writer = csv.writer(stream, delimiter='\t')
    for i in range(1000):  # Seu laço de repetição...
        valores = [...]    # Sua lista com os 100 valores...
        writer.writerow(valores)  # Aqui escreve a lista inteira no arquivo

Simple, easy and readable.

    
16.08.2018 / 15:37
0

OI, Bernardo,

You could use the python join function. It will look like this:

Form 1:

f2 = open('saida.txt','w+') # Importante usar o w+ , salvar sem apagar o'que já está lá.

f2.write(''.join([(lambda x: '%.20f \t ' %x)(q) for q in qt]) + '\n')

# Lembrar de usar o f2.close() no final do programa.

Form 2:

f2 = open('saida.txt','w+') # Importante usar o w+ , salvar sem apagar o'que já está lá.

def formatador(entrada):
    registro = ''
    for qt in entrada:
        informacao = '%.20f \t ' %qt
        registro = registro + informacao
    return registro

f2.write(formatador(qt))

I hope I have helped. :)

    
16.08.2018 / 15:19