Search code examples
pythonfilearduino

Blank lines in txt files in Python


I want to write sensor values to a text file with Python. All is working fine but one thing; in the text file, there are blank lines between each value. It's really annoying because I can't put the values in a spreadsheet. It looks like this:

Sensor values:

2

4

6.32

1

etc....

When I want it without the line breaks:

Sensor values:
1
2
3
5
8
etc...

Here's the part of the code which writes the data to file:

def write_data():
    global file_stream
    now = datetime.now()
    dt_string = now.strftime("%d-%m-%Y %H_%M_%S")
    file_stream = open("data " + dt_string+".txt", "w") # mode write ou append ?
    write_lines()

def write_lines():
    global after_id
    data = arduinoData.read()
    data2 = data.decode("utf-8")
    file_stream.write(data2)
    print(data2)
    if data2 == "F":
          print("Ca a marché")
           stopacq()
           return
    after_id = root.after(10, write_lines)

Solution

  • Add the newline attribute

    file_stream = open("data " + dt_string+".txt", "w", newline="")