How to write a large amount of values per line in Python file?

Asked

Viewed 108 times

2

I have a physical simulation code that I deal with LOTS OF INFORMATION and lots of interactions. For example, I have the calculation of the Qt load, however, it is 100 interactions and I am working with a Qt vector of size 101! I need to save the data of this Qt for each interaction I have in a file . txt:

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 that I don’t need 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'?

3 answers

6

The action you intend to perform is to join, which is given by the method join of string. This allows you to join any amount of elements of an iterable using a string as a separator between them.

Starting with a simple example, imagine you have a list of 5 elements:

elems = ['1', '2', '3', '4', '5']

If you want to show them on string separated by , can use the join:

print(','.join(elems)) # 1,2,3,4,5

In the case that has will be similar, but the difference is that each number will be separated by a \t and each element has to be formatted with the .20f that you can do at the expense of map.

Soon enough do:

texto_arquivo = ' \t '.join(map(lambda x: "%.20f" % x, qt)) + '\n'
f2.write(texto_arquivo)
  • This "text_file" suggests the name you gave the file when you gave the command "f=open...."?

  • @Bernardocecchetto No, the texto_arquivo represents the line of text that is written to the file. It’s just a variable to get a little more organized. It’s the difference between doing f2.write('a') versus texto = 'a'; f2.write(texto). They turn out to be two different ways of doing the same.

  • got it, thanks!

2

You can also use the module csv, setting the delimiter manually for the character \t. 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.

0

OI , Bernardo,

You could use python’s 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))

hope I’ve helped. :)

  • In form 1 should not have \t doing the join? And in form 2, your bow for is wrong.

  • Thanks, @Andersoncarloswoss , I already review the form 2. However 1 is to show a simple way to join without formatting..

  • You don’t need the \n to break the line? Like registro + '\n'

  • What would be of no use, so why present something like this? Not only without formatting as the whole content would be concatenated.

  • Thanks @Andersoncarloswoss for the feedback.

  • @Alexciuffa thanks for the observation.

Show 1 more comment

Browser other questions tagged

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