在我的下面的代码中,由于某种原因,即使我的输出数据与新生成的数据相同,它也会继续将输出数据写入文件...
我正在努力使它只在不同时保存,为了重新创建我的问题,至少运行三次脚本并且不应该多次打印again
import csv
def get_html_table(data):
s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<table id="gradient-style">
<tbody>\n"""
for row in data:
s += ' <tr>'
for counter, cell in enumerate(row):
s += r'<td>{}</td>'.format(cell)
s += '</tr>\n'
s += """ </tbody>
</table>
</body>
</html>"""
return s
with open('testoutput.html', 'rb') as old_html:
old_html = old_html.read()
identifyer = ""
with open('random.csv') as ifile, open('testoutput.html', 'wb') as ofile:
data = []
for counter, row in enumerate(csv.reader(ifile)):
if counter != 0:
datatoapp = [row[0], row[1], row[2], row[3]]
data.append(datatoapp)
html_data = get_html_table(data)
old_html = old_html.strip()
html_data = html_data.strip()
if old_html != html_data.strip():
if html_data:
print "again"
ofile.write(html_data)
print "done"
正如您所看到的,上面的代码将csv转换为html形式,不包含任何数据。
data,data,data,data,data
data,data,data,data,data
data,data,data,data,data
data,data,data,data,data
data,data,data,data,data
任何想法如何解决这个问题?
答案 0 :(得分:1)
这是因为你打开文件然后进行比较,因为它是相同的,它不会在文件中保存任何内容。
比较例如底部代码部分后打开文件:
import csv
def get_html_table(data):
s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<table id="gradient-style">
<tbody>\n"""
for row in data:
s += ' <tr>'
for counter, cell in enumerate(row):
s += r'<td>{}</td>'.format(cell)
s += '</tr>\n'
s += """ </tbody>
</table>
</body>
</html>"""
return s
with open('testoutput.html', 'rb') as old_html:
old_html = old_html.read()
with open('random.csv') as ifile:
data = []
for counter, row in enumerate(csv.reader(ifile)):
if counter != 0:
datatoapp = [row[0], row[1], row[2], row[3]]
data.append(datatoapp)
html_data = get_html_table(data)
if old_html != html_data:
if html_data:
with open('testoutput.html', "wb") as ofile:
ofile.write(html_data)
希望这会有所帮助:) - Hyflex
答案 1 :(得分:-1)
以下内容读取整个文件,而您可能只想阅读一行:
old_html = old_html.read()
P.S。我个人认为这种变量名称的重用非常混乱。