Search code examples
pythoncsvtimekeyboard

Writing to csv does not work when using time module


I try to save 1's to csv file but wheb I use time module nothing is saving and moves.csv file is empty, but when I use the same code without time.sleep(1) everything is working. Does anybody have any idea what might be wrong? Thanks for Your time!

import time
import keyboard

with open('moves.csv', 'w') as f:
  while True:
    if keyboard.is_pressed('space'):
      f.write('1\n')
      time.sleep(1)

Solution

  • The file is written to a buffer which only gets written to disk when the OS decides; commonly, when you close the file, or the buffer fills up.

    To see the file grow in real time, try writing a larger amount of text in each iteration.