【问题标题】:Python write serial data to the second column of my .csv filePython 将串行数据写入我的 .csv 文件的第二列
【发布时间】:2022-12-03 11:12:20
【问题描述】:

我正在读取我的串口数据,我可以将这些数据存储到 .csv 文件中。但问题是我想将我的数据写入第二列或第三列。

使用代码,数据存储在第一列中:

file = open('test.csv', 'w', encoding="utf",newline="")
writer = csv.writer(file)


while True:
    if serialInst.in_waiting:
        packet = (serialInst.readline())
        packet = [str(packet.decode().rstrip())] #decode remove \r\n strip the newline
        writer.writerow(packet)

代码 .csv 文件的输出:

Column A Column B
Data 1
Data 2
Data 3
Data 4

示例所需的输出 .csv 文件:

Column A Column B
Data1 data 2
Data3 Data 4

【问题讨论】:

    标签: python


    【解决方案1】:

    我以前没有使用过 csv.writer,但快速阅读docs,似乎表明你只能写一个一次,但您正在获取数据细胞/value at a time.

    在您的代码示例中,您已经有一个文件句柄。您不想一次写一行,而是一次写一个单元格。您需要一些额外的变量来跟踪何时换行。

    file = open('test.csv', 'w', encoding="utf",newline="")
    writer = csv.writer(file)
    
    ncols = 2 # 2 columns total in this example, but it's easy to imagine you might want more one day
    col = 0   # use Python convention of zero based lists/arrays
    
    while True:
        if serialInst.in_waiting:
            packet = (serialInst.readline())
            packet = [str(packet.decode().rstrip())] #decode remove 
     strip the newline
            if col == ncols-1:
                 # last column, leave out comma and add newline 
    
                 file.write(packet + '
    ')
                 col = 0   # reset col to first position
            else:
                 file.write(packet + ',')
                 col = col + 1
    

    在此代码中,我们使用文件对象的 write 方法而不是使用 csv 模块。请参阅these docs 了解如何直接读写文件。

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 2014-09-06
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2011-11-23
      相关资源
      最近更新 更多