1

im a beginner in python and im trying to read a csv file into a python dictionary to generate html tables. i have 30 columns in my file and i want first 4 columns in csv file into my html table as columns and next six columns in another html table and so on..some of my columns includes strings and some includes integers csv file is like:

oposition mat won lost total overs
aa        5   3   2    400   20
bb        4   2   2    300   20
cc        4   3   1    100   19

im trying to get the data as :

<table>
<tr><td>aa</td> <td>5</td> <td>3</td> <td>2</td></tr>
<tr><td>bb</td> <td>4</td> <td>2</td> <td>2</td></tr>
<tr><td>cc</td> <td>4</td> <td>3</td> <td>1</td></tr>
</table>

so far my codes are;

infile = open("minew.csv", "r")
mydict = {}
for line in infile:
    words = line.split(",") 
    oposition = words[0]
    mat = words[1]
    won = words[2]
    lost = words[3]
    mydict[oposition] = oposition
    mydict[mat] = int(mat)
    mydict[won] = int(won)
    mydict[lost] = int(lost)

print("<table>")
for o,m,w,l in mydict.keys():
    print("<tr><td>{op}</td> <td>{mt}</td> <td>{wi}</td> <td>{lo}</td>
    </tr>".format(
        op = mydict[oposition],
        mt = mydict[mat]
        wi = mydict[won]
        lo = mydict[lost]))
print("</table>")

i cant make my codes working. please anyone help me out. much appreciated

2
  • What is it currently outputting? Please add that to the question. Commented May 25, 2017 at 13:09
  • ----> 7 mat = words[1] IndexError: list index out of range Commented May 25, 2017 at 13:46

3 Answers 3

4

Don't reinvent the wheel, use existing csv package:

import csv
with open('minew.csv') as csvfile:
     reader = csv.DictReader(csvfile, delimiter='\t')
     for row in reader:
         print('<tr>')
         for fn in reader.fieldnames:
             print('<td>{}</td>'.format(row[fn]))
         print('</tr>')
Sign up to request clarification or add additional context in comments.

Comments

1

It wasn't clear to me that there is only a single character between the columns in your input file, such as a tab ('\t`), in which case I think the csv module might not be applicable. Here's another way of doing it.

print ('<table>')
with open('minew.csv') as minew:
    first = True
    for line in minew.readlines():
        if first:
            first = False
        else:
            values = line.split()
            print ('<tr>', end='')
            for value in values:
                print ('<td>%s</td>' % value, end='')
            print ('</tr>')
print ('</table>')

I think the principal difference between this and your code is that I've used split() instead of split(',') because there is whitespace between the columns.

This is the output.

<table>
<tr><td>aa</td><td>5</td><td>3</td><td>2</td></tr>
<tr><td>bb</td><td>4</td><td>2</td><td>2</td></tr>
<tr><td>cc</td><td>4</td><td>3</td><td>1</td></tr>
</table>

2 Comments

changed the code and my csv file a bit and this works. im thinking of creating a html page and put this table inside that page. so instead of printing the data i tried to assign the same output into a new variable but my codes are going nowhere so far. is that possible to put the output into a html page editor code list or im thinking of copy and paste the output data into my html page editor. please help me out
What kind of a variable do you want the output to go into? A string, list of strings? Something else? I'll help if I can.
0

I think there are some points you'd better know:

1, you have to skip the header with next() when you open the csv file

2, No need to create a new dict to do that, and keep in mind python dict is not ordered.

3, Just use the element in the first loop, as you have already catch them.

4, Close the file after the operation is always a good practice.

Suppose you have csv file:

oposition mat won lost total overs
aa        5   3   2    400   20
bb        4   2   2    300   20
cc        4   3   1    100   19

Based on your logic, code goes here:

infile = open("minew.csv", "r")
next(infile)
print("<table>")
for line in infile:
    words = line.strip().split() 
    oposition = words[0]
    mat = words[1]
    won = words[2]
    lost = words[3]
    print("<tr><td>{op}</td> <td>{mt}</td> <td>{wi}</td> <td>{lo}</td></tr>".format(op = oposition,mt = mat,wi = won,lo = lost))
print("</table>")
infile.close()

Output:

<table>
<tr><td>aa</td> <td>5</td> <td>3</td> <td>2</td></tr>
<tr><td>bb</td> <td>4</td> <td>2</td> <td>2</td></tr>
<tr><td>cc</td> <td>4</td> <td>3</td> <td>1</td></tr>
</table>

4 Comments

IndexError: list index out of range
is your csv file format same as the one in my answer?
IndexError Traceback (most recent call last) <ipython-input-12-462acbf24868> in <module>() 5 words = line.strip().split(",") 6 oposition = words[0] ----> 7 mat = words[1] 8 won = words[2] 9 lost = words[3] IndexError: list index out of range
@Dush please check my updated answer, I have noted your csv file delimiter is space, then just change words = line.strip().split(",") to words = line.strip().split()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.