save data from a command to a csv file in python
Question: I want to save the result of a command in a csv file. I have this code for the
moment :

    
    
    import sys
    import os
    import time
    import datetime
    import subprocess
    import csv
    
    with open("compteur_data.csv","a") as csvfile:
                date = datetime.datetime.today()
                wtr=csv.writer(csvfile)
                wtr.writerow(['Date/Heure','DATA']) #pillar title
                while True:
                    ts = time.time()
                    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
                    print '..............................', st
                    sys.stdout.flush()
                    cmd = 'sdm120c -a 1 -b 2400 -P N -S 2 -j 20 -z 1 /dev/ttyUSB0'
                    (c_stdin,c_stdout,c_stderr)=os.popen3(cmd,'r')
                    out=c_stdout.read()
                    print out
                    c_stdin.close()
                    c_stdout.close()
                    c_stderr.close()
    
                    wtr.writerow([date,out])
                    time.sleep(5)
    

My purpose is to collect the data from a sdm120c , then, save the data in a
csv file. On my python shell i can see all the data i want save every 5
seconds but when i open the target csv file nothing is write in .. Maybe some
one can ask me where is my mistake ? please .


Answer: Add a call to flush the buffered contents to the file. This is achieved by
using the call: csvfile.flush()

    
    
    with open("compteur_data.csv","a") as csvfile:
        date = datetime.datetime.today()
        wtr=csv.writer(csvfile)
        wtr.writerow(['Date/Heure','DATA']) #pillar title
        while True:
            ts = time.time()
            st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
            print '..............................', st
            sys.stdout.flush()
            cmd = 'sdm120c -a 1 -b 2400 -P N -S 2 -j 20 -z 1 /dev/ttyUSB0'
            (c_stdin,c_stdout,c_stderr)=os.popen3(cmd,'r')
            out=c_stdout.read()
            print out
            c_stdin.close()
            c_stdout.close()
            c_stderr.close()
    
            wtr.writerow([date,out])
    
            #New call to flush added below
            csvfile.flush()
    
            time.sleep(5)
    

