Skip to content Skip to sidebar Skip to footer

Looping Through Dictionary Built From Csv And Write Certain Key Values To File

I am trying to open a file and read it into a dictionary. I've done this successfully, but I need to write the 'values' to variable and then take the variable and write it to anoth

Solution 1:

I'm not sure what your desired output is. What about this? In this code, I first write the beginning of the html file, then I loop through the csv file and add a few spans for each row of the file.

import csv

with open('registrant_data.csv') as csvFile:
    readCSV = list(csv.DictReader(csvFile))

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


    for row in readCSV:
        myWriteFile.write('<span class="font22">' + row['firstname'] +'</span>\n'
                          '<span class="font12">' + row['lastname'] +'</span>\n'
        # here add other info for each person

    myWriteFile.write('</div>\n'
                      '</body>\n')

Post a Comment for "Looping Through Dictionary Built From Csv And Write Certain Key Values To File"