Problem writing to the Python file

1

I have an arduino that sends values through the serial port, what I want to do is read the data and save it in a .txt file but it does not save the data. Can you help me?

    import time

try:
    import serial
    arduino = serial.Serial('COM5', baudrate=9600, timeout=1.0)

    # Nota: provocamos un reseteo manual de la placa para leer desde
    # el principio, ver http://stackoverflow.com/a/21082531/554319
    arduino.setDTR(False)
    time.sleep(1)
    arduino.flushInput()
    arduino.setDTR(True)
except (ImportError, serial.SerialException):
    # No hay módulo serial o placa Arduino disponibles
    import io
with arduino:
    while True:
        try:

            # En Python 3 esta función devuelve un objeto bytes, ver
            # http://docs.python.org/3/library/stdtypes.html#typebytes    
            f = open ('holamundo.txt','w')            
            line = arduino.readline()
            f.write(line)
            f.close()
            # Con errors='replace' se evitan problemas con bytes erróneos, ver
            # http://docs.python.org/3/library/stdtypes.html#bytes.decode
            # Con end='' se evita un doble salto de línea
            print(line.decode('ascii', errors='replace'), end='')
        except KeyboardInterrupt:
            print("Exiting")
            break
    
asked by David 31.12.2018 в 16:28
source

1 answer

2

Since each time you go through the loop, you reopen the file in writing mode, which previously would have been deleted before writing the new value.

Therefore, when leaving the loop the file will contain only what was written in the last iteration of the loop.

What you can do is open the file in "append" mode so that the lines you type are added to what was already there, like this:

        f = open ('holamundo.txt','ab')            
        line = arduino.readline()
        f.write(line)
        f.close()
    
answered by 31.12.2018 / 19:02
source