2017-06-11 8 views
0

ブラウザのWebサイトでcsvファイルのデータを使用してテーブルを作成しようとしていますが、それを取得できないようです。基本的には、同じフォルダにpythonプログラムとcsvファイルを作成しようとしています。私のウェブサイトを参照する人は、csvファイルのデータをテーブルとして表示できます。優れています。これは私がこれまで持っているものです。pythonを使用してcsvFileObjectからデータのテーブルを作成する方法は?

#!/usr/bin/python 
print 'content-type: text/html\n' 
import csv 
import cgi 
import cgitb 
cgitb.enable() 

reader = csv.reader(open('data.csv', 'rb')) 
print ''' 
<!DOCTYPE html> 
<html> 
    <head> 
    <h1> Diabetes Across Different Groups</h1> 
    </head> 
    <body> <table border='1'> 
    <th>Demographic</th> 
    <th>Data Years</th> 
    <th>Estimated Number of Diabetics</th> 
    <th>Percent of Adults in that Demographic</th> 
    <th>Standard Error for Percent</th>''' 
rownum = 0 
    for row in reader: # reads rows from the CSV file 
     if rownum == 0: 
      print '<tr>' 
      for column in row: #reads a column from row 
       print '<td>' + column + '</td>' 
      print '</tr>' 

    #write all other rows 
    else: 

     rownum += 1 #increment row 



print ''' </table> 
     <p> </p> 
    </body> 
</html>''' 
+0

を 'Pandas'は' to_html() '関数を持っています。だから 'import pandas as pd'のようなことを行い、csvファイル' df = pd.read_csv( "data.csv")を読み込みます。もし正しくフォーマットされていれば、 'html_table = df.to_html()'で与えられるはずですあなたはCSVファイルのHTML版です。 HTML出力をWebサイトに追加/挿入することができます –

答えて

0

次のようにあなたのコードを向上させることができます:

import csv 
import cgi 
import cgitb 

cgitb.enable() 

print 'content-type: text/html\n' 

print ''' 
<!DOCTYPE html> 
<html> 

<head> 
<title>Diabetes Across Different Groups</title> 
</head> 

<body> 
<h1>Diabetes Across Different Groups</h1> 
<table border='1'> 
    <th>Demographic</th> 
    <th>Data Years</th> 
    <th>Estimated Number of Diabetics</th> 
    <th>Percent of Adults in that Demographic</th> 
    <th>Standard Error for Percent</th>''' 

with open('data.csv', 'rb') as f_input: 
    csv_input = csv.reader(f_input) 
    #header = next(csv_input)  # optionally skip header in CSV file 

    for row in csv_input: # reads a row at a time from the CSV file 
     print ' <tr><td>{}</td></tr>'.format('</td><td>'.join(row)) 

print '''</table> 
<p></p> 
</body> 
</html>''' 
関連する問題