使用python在csv中每一行的末尾附加字典或值列表 [英] Append Dictionary or list of values at the end of each row in csv using python

查看:50
本文介绍了使用python在csv中每一行的末尾附加字典或值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to append a list of values at the end of each row of a csv file except the header.

我尝试了以下代码,但它删除了 csv 文件中的所有行,并且没有向 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.

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 的每一行,除了像下面这样的标题值.

I want to append the following values to a csv file which is already created. I mean the dict values should be appended to each row of csv except the header values like below.

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

{'angry': 0.15, 'disgust': 0.0, 'fear': 0.05, 'happy': 0.06, 'sad': 0.24, 'surprise': 0.02, 'neutral': 0.49}

我也分享了我的截图csv 文件截图

推荐答案

以下是将列附加到现有 CSV 的基本示例:

Here's a basic example of appending columns to an existing CSV:

data.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(最终版)

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

这篇关于使用python在csv中每一行的末尾附加字典或值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆