简体   繁体   English

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

[英]Append Dictionary or list of values at the end of each row in csv using python

I want to append a list of values at the end of each row of a csv file except the header.我想在 csv 文件的每一行末尾附加一个值列表,但标题除外。

I have tried following code but it deletes all the rows from csv file and does not appends any value to the csv file.我尝试了以下代码,但它删除了 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)

I want to append the following values to a csv file which is already created.我想将以下值附加到已创建的 csv 文件中。 I mean the dict values should be appended to each row of csv except the header values like below.我的意思是 dict 值应该附加到 csv 的每一行,除了下面的标题值。

{'angry': 0.15, 'disgust': 0.0, 'fear': 0.05, 'happy': 0.06, 'sad': 0.24, 'surprise': 0.02, 'neutral': 0.49} {'愤怒':0.15,'厌恶':0.0,'恐惧':0.05,'快乐':0.06,'悲伤':0.24,'惊讶':0.02,'中性':0.49}

I am also sharing the screenshot of my csv file screenshot我也分享了我的csv 文件截图的截图

Here's a basic example of appending columns to an existing CSV:这是将列附加到现有 CSV 的基本示例:

data.csv (original)数据.csv(原始)

col1,col2,col3
1,2,3
4,5,6
7,8,9

test.py测试文件

import csv

with 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)

data.csv (final) data.csv(最终版)

col1,col2,col3,angry,disgust,fear,happy,sad,surprise,neutral
1,2,3,0.15,0.0,0.05,0.06,0.24,0.02,0.49
4,5,6,0.15,0.0,0.05,0.06,0.24,0.02,0.49
7,8,9,0.15,0.0,0.05,0.06,0.24,0.02,0.49

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

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