Failed writing a list in a csv file with python 3

147 Views Asked by At

I have a python script, on my Raspberry pi 3, who managed the service_perfdata(.csv) of nagios. I have to build this csv file for is reading in ruby with dashing (an IHM) But after running the following code, my new csv file is empty. there is my code:

#!/usr/bin/python3.4.2
# -*- coding: utf-8 -*-

import time
import csv
import sys
import os
import re

n=8
while True: 
    with open("/usr/local/nagios/var/service-perfdata.csv","r") as f:
        ligne=list(f)
        clean=str(ligne)
        int_list = [int(s) for s in re.findall ('\\d+',clean)] #extract int from the csv file of nagios
        n=8
        i=n
        while i<len(int_list): # add a line return at n step
            int_list.insert(i,"\n")
            i +=(n+1)

        j=3
        m=0
        x=1
        y=4
        while j<len(int_list): #concatenation of the date 
            int_list[m:j] = ['/'.join(map(str,int_list[m:j]))]
            m+=7
            j+=7

        while y<len(int_list):   #concatenation of the time 
            int_list[x:y] = ['-'.join(map(str,int_list[x:y]))]
            x+=5
            y+=5


    with open ("RAM.csv","w") as g :
        wtr = csv.writer(g,delimiter=',')
        w=0
        z=5
        while z < len(int_list): #rewrite of the list,line by line in my new csv file
            wtr.writerow(int_list[w:z])
            print (int_list[w:z])
            z+=5
            w+=5
        time.sleep(30)

and when I run it, i have this result in the Python Shell:

['12/20/2016', '0-49-36', 1032642560, 12, '\n']
['12/20/2016', '0-54-35', 1021329408, 12, '\n']
['12/20/2016', '0-59-34', 1023262720, 12, '\n']
['12/20/2016', '1-4-35', 1018642432, 12, '\n']
...

This is the result I want in my csv file, but I can't see any data in the file when I open it..maybe some body have an idea ? actually, I am new in python, so i am available to any comment on my code.

1

There are 1 best solutions below

3
On

The data is actually written to the file. Probably you can't see it because you keep it open most of the time. I don't know why you are doing that, maybe you should put the program to sleep after the file has been closed.