使用python在csv中每行末尾附加字典或值列表

我想在csv文件的每一行末尾附加一个值列表,除了标题。


我尝试了以下代码,但它从csv文件中删除了所有行,并且不会将任何值附加到csv文件中。


import tensorflow

from fer.fer import FER

import cv2

from os import listdir

from os.path import isfile, join

import numpy

import csv




f1 =     open("C:/Yasir/Thesis/4/FaceDetectionLatest/bin/Debug/Data/demoScoringData9.csv",   "a+")

reader = csv.reader(f1)

images = numpy.empty(len(onlyfiles), dtype=object)

for n in range(0, len(onlyfiles)):

    images[n] = cv2.imread( join(mypath,onlyfiles[n]) )

    # cv2.imshow(join(mypath,onlyfiles[n]),0)

    img = cv2.imread( join(mypath,onlyfiles[n]) )

    detector = FER()

    emotion = detector.detect_emotions(img)

    dict = emotion[0]

    emoList = dict['emotions']

    dict_writer = csv.DictWriter(f1, emoList)

    dict_writer.writerow(emoList)

我想将以下值附加到已创建的csv文件中。我的意思是,除了如下所示的标题值之外,dict值应该附加到每行csv中。


{'愤怒': 0.15, '厌恶': 0.0, '恐惧': 0.05, '快乐': 0.06, '悲伤': 0.24, '惊喜': 0.02, '中性': 0.49}

我还在分享我的csv文件截图的屏幕截图


慕沐林林
浏览 144回答 1
1回答

MYYA

下面是将列追加到现有 CSV 的基本示例:数据.csv(原始)col1,col2,col31,2,34,5,67,8,9test.pyimport csvwith open('data.csv',newline='') as fin:    r = csv.DictReader(fin)    lines = list(r)with open('data.csv','w',newline='') as fout:    # Create writer with existing column headers plus new column headers    w = csv.DictWriter(fout,fieldnames=r.fieldnames + 'angry disgust fear happy sad surprise neutral'.split())    w.writeheader()    for line in lines:        emolist = {'angry': 0.15, 'disgust': 0.0, 'fear': 0.05, 'happy': 0.06, 'sad': 0.24, 'surprise': 0.02, 'neutral': 0.49}        line.update(emolist)        w.writerow(line)数据.csv (最终)col1,col2,col3,angry,disgust,fear,happy,sad,surprise,neutral1,2,3,0.15,0.0,0.05,0.06,0.24,0.02,0.494,5,6,0.15,0.0,0.05,0.06,0.24,0.02,0.497,8,9,0.15,0.0,0.05,0.06,0.24,0.02,0.49
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python