首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >继续使用python的csv文件中的列。

继续使用python的csv文件中的列。
EN

Stack Overflow用户
提问于 2018-08-09 07:42:49
回答 1查看 279关注 0票数 0

我有一个问题,继续写我的数据在csv文件。我需要一个程序来检测,如果有一个csv文件为我的测量-数据。如果没有,它就会产生。当csv-文件是新生成的,数据将写入列的csv-文件中,在带有变量cycle = 0的标题之后。

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

我已经写了一个程序,可以检测是否有一个文件,但与连续的行,我有问题。我希望有人能帮我。

代码语言:javascript
运行
复制
# 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()`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-09 09:26:55

使用open()打开文件时,有“a”选项将新行追加到末尾:

‘’打开以便写入,如果文件存在,则追加到文件的末尾。

下面是一个使用csv Python标准库的示例:

代码语言:javascript
运行
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51761404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档