How to write CSV file data without erasing existing data

Asked

Viewed 271 times

0

I need to save data in CSV file without it deletes the existing data in the file, just create a new line with the informed data

 material=str(input('Informe o material: '))

 mod_elasticidade=float(input('Informe o modulo de elasticidade do material:'))

 tensao_escoamento=float(input('Informe a tensao de escoamento do material:'))

 historico = open("historico.csv","w")

 linha=str(material)+";"+str(mod_elasticidade)+";"+str(tensao_escoamento)

 historico.write(linha)

 historico.close()

1 answer

4

Just change the w for a+, thus:

historico = open("historico.csv", "a+")

linha=str(material)+";"+str(mod_elasticidade)+";"+str(tensao_escoamento)

historico.write(linha)

historico.close()

ps: use the with, so when the block finishes it closes the file alone, so:

material = str(input('Informe o material: '))

mod_elasticidade = float(input('Informe o modulo de elasticidade do material:'))

tensao_escoamento = float(input('Informe a tensao de escoamento do material:'))

linha = str(material)+";"+str(mod_elasticidade)+";"+str(tensao_escoamento)

with open("historico.csv", "a+") as historico:
    historico.write(linha)
  • I swapped "w" for "a+" does not erase the existing data in the file, however it writes the new information in the same line of the existing data, I need to write the data in the next blank line of the file and not in the same line

  • @Fabiodalzotto but it was for the a+ do this, who writes on existing lines is the a without the sign of +, the plus sign moves the pointer to the end, unless it is a BUG, you must have done something else in your script that failed at this, it just wasn’t meant to occur.

Browser other questions tagged

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