使用python写入CSV文件 [英] Writing into CSV file using python

查看:220
本文介绍了使用python写入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些简单的代码我写了。数据不会累积在CSV文件中;
有人可以共享代码从串行端口读取数据并将其记录到CSV文件?

Here some simple code I have written. Data is not accumulated in the CSV file; can someone share code to read data from serial port and log this to a CSV file?

import serial
import csv
import string
import os
import time
import sys

def main():
    pass

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

    result_statememt=("date","zenith","elevation","azimuth","conv_elevation");
    result.writerow(result_statememt)
    f.close()
    while(count<10):
        #time.sleep(60)
        ser=serial.Serial()
        ser.port=3
        ser.baudrate=9600
        ser.open()
        str=ser.read(50)
        val=str.split(":")
        lines=str.split("\r\n")
        count=count+1
        print count
        f=open("test.txt","a+")
        result=csv.writer(f,delimiter=',')
        result.writerow()
        f.close()

    f.close()
    ser.close()


推荐答案

如前所述,由于您没有向 result.writerow()传递任何内容,因此没有任何内容写入CSV文件。但我也担心你从串行端口一次读取50个字节,然后分割在字符,然后在 \r\\\
分隔符。我不认为这会做你想要的。

As noted, since you're not passing anything to result.writerow() nothing is being written to the CSV file. But I'm also concerned that you're reading 50 bytes at a time from the serial port, then splitting it on the : character and then splitting it on a \r\n delimiter. I don't think this is going to do what you want.

我的猜测是,你期望串行端口传递由 \r\\\
,每行包含一组由分隔的字段,并且要将这些字段写入CSV文件。我建议尝试这样的替代:

My guess is that you are expecting the serial port to deliver lines terminated by \r\n, each line consisting of a set of fields separated by :, and you want to write these fields to a CSV file. I'd recommend trying something like this instead:

with open("test.txt", "wb") as output_file:
    csv_out = csv.writer(output_file, delimiter=',', dialect='excel-tab')
    csv_out.writerow("date","zenith","elevation","azimuth","conv_elevation")

    ser=serial.Serial(port=3, baudrate=9600, timeout=60)
    ser.open()
    for count in range(10):
        str = ser.readline().rstrip()
        csv_out.writerow(str.split(':'))
    ser.close()

我没有使用Python serial 模块,测试这个,但基于我的阅读模块文档,这应该更接近你想做什么。我认为读取超时时间以秒为单位,因此如果串行端口在一分钟内没有产生任何数据,则会超时。

I haven't used the Python serial module and don't currently have hardware to test this, but based on my reading of the module documentation this should be closer to what you want to do. I think the read timeout is measured in seconds, so this will time out if the serial port doesn't produce any data for one minute.

这篇关于使用python写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆