繁体   English   中英

使用python继续在csv文件中的列

[英]Continues columns in a csv-file with python

我在继续将数据写入csv文件时遇到问题。 我想要一个程序来检测我的测量数据是否有csv文件。 如果没有,它将生成。 生成新的csv文件时,数据将写入变量为cycle = 0的标题后的列中的csv文件中。

如果csv文件存在,则应在csv的最后一行之后连续写入数据。 可变cycle应继续。

我编写了一个程序,该程序可以检测是否有文件,但是连续不断地出现问题。 我希望有一个人可以帮助我。

# mes = Array with 20 spaces filled with the Numbers 0-19

date = time.strftime("%d/%m/%Y")

def write(cycle, mes):

    if os.path.exists('/home/pi/Documents/Ventilatorprüfstand_Programm/out.csv') is True: #does the out.csv existate?
        print("Do something")
        out = open('out.csv', 'w')
        data = [[cycle, mes[0],mes[1],mes[2],mes[3],mes[4],mes[5],mes[6],mes[7],mes[8],mes[9],mes[10],mes[11],mes[12],mes[13],mes[14],mes[15],mes[16],mes[17],mes[18],mes[19], date]]
        line = cycle+1    
        for row in data:
            for line in row:
                out.write('%s;' % line)
            out.write('\n')   
        out.close()

    else:
        print("Do another something")
        header = lookuptable.names()
        out = open('out.csv', 'w')
        for row in header:
            for column in row:
                out.write('%s' % column)
            out.write('\t')
        out.write('\n')

        data = [[cycle, mes[0],mes[1],mes[2],mes[3],mes[4],mes[5],mes[6],mes[7],mes[8],mes[9],mes[10],mes[11],mes[12],mes[13],mes[14],mes[15],mes[16],mes[17],mes[18],mes[19], date]]


        for row in data:
            for column in row:
                out.write('%s;' % column)
            out.write('\n')
        out.close()`

使用open()文件时,可以使用选项'a'将新行添加到末尾:

可写的'a',追加到文件末尾(如果存在)

这是使用csv Python标准库的示例:

import csv
import os
import random

headers = ['cycle', 'date', 'speed', 'temp', 'power']

new_data = [[random.randint(0, 100) for _ in range(3)] for _ in range(2)]
date = '00/01/02'
cycle = 1

#  Copy the data and include the date and the cycle number:
full_rows = [ [cycle, date, *row] for row in new_data ]

filename = 'example.csv'

# Check if the file exist, if not create the file with header
if not os.path.exists(filename):
    print('creating a new file')
    with open(filename, 'w') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',')
        csvwriter.writerow(headers)  # add the header

# Append the data to the file
with open(filename, 'a', newline='') as csvfile:  # note the 'a' option
    csvwriter = csv.writer(csvfile, delimiter=',')
    csvwriter.writerows(full_rows)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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