-2

Hello is there anyway i can open a file with excel while is python programm is running? When i open it, it always has no data in it. Only if the Programm finishes Data is in the CSV. So is there a way that the csv writers writes data instantly and not only after the programm finishes?

This is how i open the file

filename = "Messung_von_" + datetime.datetime.now().strftime("%Y_%m_%d-%H_%M_%S")
file=open (filename+ ".csv", "wb")
c = csv.writer(file) #CSV

then in a for loop im writing this to the file

c.writerow([x_in_plot,y_in_plot,get_noise()])

The X and Y Values are counted in the for loop, the function get_noise() is a function where i just read a value out of a device

after the for loop i close the csv with

file.close()

thanks

tMonation
  • 1
  • 3
  • Probably your Python program is flushing the output buffer only at the end. You need to provide more details on it – usr-local-ΕΨΗΕΛΩΝ Nov 28 '16 at 10:53
  • Open a file while it's being modified by another program is asking for trouble. What are you trying to do ? – polku Nov 28 '16 at 10:55
  • i edited the question does this information help you? – tMonation Nov 28 '16 at 10:58
  • This should answer your question: http://stackoverflow.com/questions/18984092/python-2-7-write-to-file-instantly , either use flush() method after each write or open file in unbuffered mode. – Zelo Nov 28 '16 at 11:12
  • As @Zelo says, this is due to the fact that the default open file mode is buffered which means that python internally buffers writes to the file and then only actually writes data to the disk when it hits a buffer limit. If the file is small enough you won't actually see anything written to the file until the stream is closed, where it internally flushes and actually writes to disk. The best solution for this seems to be to open the file in unbuffered mode, like so: `file=open (filename+".csv", "wb", 0)` The third parameter to open is buffering mode where 0 is unbuffered, 1 is buffered. – Dillanm Nov 28 '16 at 11:54

1 Answers1

-1

File.flush() during the for loop fixed it for me!

tMonation
  • 1
  • 3