为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕沐林林 2022-08-16 16:29:05
我想在csv文件的每一行末尾附加一个值列表,除了标题。我尝试了以下代码,但它从csv文件中删除了所有行,并且不会将任何值附加到csv文件中。import tensorflowfrom fer.fer import FERimport cv2from os import listdirfrom os.path import isfile, joinimport numpyimport csvf1 =     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文件截图的屏幕截图
查看完整描述

1 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

下面是将列追加到现有 CSV 的基本示例:


数据.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)

数据.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


查看完整回答
反对 回复 2022-08-16
  • 1 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信