Python:打印从cs读取的字典列表中的特定值

2024-04-24 00:05:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何将csv文件读入字典,然后用python从字典中打印出特定的值。CSV file example。我想把选中的行打印出来。我在这方面是新手,我试过一些循环,但循环会直接转到最后一个人。你知道吗

import csv
with open('data.csv') as csvFile:
readCSV = list(csv.DictReader(csvFile))
for row in readCSV:
    person1 = row['firstname'] + ' ' + row['lastname']
with open('nametags8gen.html', 'w+') as myWriteFile:
myWriteFile.write('<!DOCTYPE html> \n'
                  '<html>\n'
                  '<head>\n'
                  '<title>natetag8</title>\n'
                  '<link href="styles/nametags8.css" type="text/css" rel="stylesheet" />\n'
                  '</head>\n'
                  '<body>\n'
                  '<header>\n'
                  '</header>\n'
                  '<main class="mainContainer">\n'
                  '<div class"textBoxContainer">\n'
                  '<div class="textContainer">\n'
                  '<span class="font22">' + person1 +'</span>\n'
                  '<span class="font12">Smith</span>\n'
                  '<span class="font14">Web Developer</span>\n'
                  '<span class="font12">Regis University</span>\n'
                  '<span class="font12">Denver, CO</span>\n'
                  '</div>\n')

这个循环通过并抓住最后一个人,而不是我需要的特定的人。你知道吗

在'写'部分,我将把个人信息,特别是在那个地方说'person1'在我的html模板是一个名字和姓氏将去,我从CSV文件。我不知道如何使循环在某个人/行上停止以获取他们的信息,例如名字或地址。你知道吗


Tags: 文件csvcsvfilediv字典htmlaswith
1条回答
网友
1楼 · 发布于 2024-04-24 00:05:21

执行以下操作:

import csv
l = []

with open('inputfile.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        l.append(row)

# If you need say for example the firstname
for val in l:
    print (l['firstname'])

虽然它仍然不清楚没有代码,你到底想实现什么。你知道吗

相关问题 更多 >