简体   繁体   中英

Separating values from list and write into csv file

I have the below piece of code with which I wanted to separate date:07/12/13 and write it into csv file. However, I wasn't able to separate element from list. I have tested the list component over the .py script, which worked fine, but when I run the script it's giving an error.

def main():
    pass

if __name__ == '__main__':
    main()
    count=0
    f=open("test.csv","w+");
    result = csv.writer(f,delimiter=',', dialect='excel-tab')

    result_statememt=("date","time","Zenith","Azimuth","Elevation","conv_elevation");
    result.writerow(result_statememt)
    f.close()
    while(count<5):
        #time.sleep(60)
        ser=serial.Serial()
        ser.port=2
        ser.baudrate=9600
        ser.open()
        str=ser.read(109)
        print str
        val=str.split(":")
        print val
        print "\n"
        lines=str.split("\r\n")
        print lines
        wst=[]

        print line
        wst=[]
     for line in lines[:]:
              line=lines.split(":")
               print line

        f=open("test.csv","a+")
        result=csv.writer(f,delimiter=',')

        count=count+1



        #lines=str.split("\r\n")

        #print count
        #f=open("test.txt","a+")
        #result=csv.writer(f,delimiter=',')
        #result.writerow()
        f.close()

    f.close()
    ser.close()

Output window of program:

Serial.port received data:
date is:7/12/16
time is:24-0-0
Zenith:104.85
Azimuth:110.40
Elevation:-14.85
Converted Elevation:15.79
val out put :
['date is', '7/12/16\r\ntime is', '24-0-0\r\nZenith', '104.85\r\nAzimuth', '110.40\r\nElevation', '-14.85\r\nConverted Elevation', '15.79\r\n']
lines output:

['date is:7/12/16', 'time is:24-0-0', 'Zenith:104.85', 'Azimuth:110.40', 'Elevation:-14.85', 'Converted Elevation:15.79', '']

The relevant missing bit of code is:

import csv
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

You are not writing with the iteratable so failing. Also you should only open the file once and close it once .

Here are what I understand about your problem:

  • Read data from serial port
  • Data consists of 6 lines
  • Each line consists of a tag (eg 'date is'), a colon and a value (eg '7/12/16')
  • You want to capture the values and write them to a CSV file (with header)

Let's start with trying to process one set of data (6 lines) before we can process more. As I understood, a set of data might look like:

date is:7/12/16
time is:24-0-0
Zenith:104.85
Azimuth:110.40
Elevation:-14.85
Converted Elevation:15.79

The lines are \\r\\n , but it does not matter much. Pretend that we obtained the data by:

>>> data  = 'date is:7/12/16\r\ntime is:24-0-0\r\nZenith:104.85\r\nAzimuth:110.40\r\nElevation:-14.85\r\nConverted Elevation:15.79'

If we split the data by lines:

>>> data.splitlines()
['date is:7/12/16', 'time is:24-0-0', 'Zenith:104.85', 'Azimuth:110.40', 'Elevation:-14.85', 'Converted Elevation:15.79']

Now, we can split each line at the colon:

>>> [line.split(':')[1] for line in data.splitlines()]
['7/12/16', '24-0-0', '104.85', '110.40', '-14.85', '15.79']

The above said, *for each line from our data, we split the line at the colon and take the second part (the first part is at index 0, second part is at index 1). This is the row we want to write to the output file.

Now that we know how to process the line, we can put it in a loop (5 times in your case). Also, I cleaned up the code a bit by putting the serial port initiation code at the beginning. That way, we only initialize it once and close once. Here is the code:

import csv

if __name__ == '__main__':
    # Init serial line
    ser = serial.Serial()
    ser.port = 2
    ser.baudrate = 9600
    ser.open()

    with open('test.csv', 'w+') as f:
        result = csv.writer(f, delimiter=',', dialect='excel')
        result.writerow(['date','time','Zenith','Azimuth','Elevation','conv_elevation']);
        for count in range(5):
            data = ser.read(109)
            row = [line.split(':')[1] for line in data.splitlines()]
            result.writerow(row)

    ser.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM