Try suppressing the flush.
You can use an IOBytes buffer and then write the buffer out to file.? That's probably the best/fastest solution.
Or you could try writing in chunks:
import os
import serial
port = "/dev/ttyACM0"
baudRate = 460800
try:
? ? ser = serial.Serial(port, baudRate)
except serial.SerialException as e:
? ? print(f"Error opening {port}: {str(e)}")
? ? exit(1)
try:
? ? with open("sound_data.csv", "w") as outFile:
? ? ? ? count = 0
? ? ? ? chunk_size = 100? # Define the size of each chunk
? ? ? ? data_chunk = []? # Initialize the list to hold data lines
? ? ? ? while count < 1000:
? ? ? ? ? ? data = ser.readline().decode().strip()
? ? ? ? ? ? if data:
? ? ? ? ? ? ? ? data_chunk.append(data + "\n")
? ? ? ? ? ? ? ? count += 1
? ? ? ? ? ? ? ? # When the chunk size is reached, write the chunk to the file
? ? ? ? ? ? ? ? if len(data_chunk) == chunk_size:
? ? ? ? ? ? ? ? ? ? outFile.writelines(data_chunk)
? ? ? ? ? ? ? ? ? ? data_chunk = []? # Reset the chunk
? ? ? ? # Write any remaining data in the chunk after the loop ends
? ? ? ? if data_chunk:
? ? ? ? ? ? outFile.writelines(data_chunk)
finally:
? ? ser.close()