Doubt about float and int

1

I have a program that reads me file data excel and csv and writes them in txt . The problem I have is that one of the columns that he reads are decimals and when writing them he puts them all as decimal. The issue is that I just want to write to me as decimal those that are different from 0; whereas if the decimal is 0, I want you to write it as an integer.

For example:

si el dato que lee es: 3.1    
quiero que escriba: 3.1    
pero si el dato que lee es: 3.0    
quiero que escriba: 3*

I put part of the code:

#Leo los datos y los almaceno en una lista
hoja = miExcel.sheet_by_index(0)
for row in range(1, hoja.nrows, 1):
    dato = hoja.cell_value(row, 2)
    listaDatos.append(pInstEol)
#Escribo los datos fila a fila iterando por indice
with open(ficheroTxt, 'w') as f:
    for indiceXls, nombreDato in enumerate (listaNombreDato):
        dato = listaDatos[indiceXls]
        f.write(str(dato) + ... + '\n') 

I hope to have explained myself well. How can I do it, because or all float or all int . I do not know how to make that exception.
Thanks

    
asked by Tercuato 15.01.2018 в 13:28
source

1 answer

2

For that you can format your text string ( dato ) with String Formatting Operations.

Like this:

f.write(('%g' % dato) + ... + '\n') 

If you look at segment '%g' % dato is composed of 3 things:

  • '%g' (format to be used)
  • % (operator to execute the format)
  • dato (string to which we are going to format)

You can find the usefulness of the '%g' format and many more in the official python documentation:

link

Greetings.

    
answered by 16.01.2018 / 13:16
source