好的,基本上我有一个csv文件,有不同的值。我希望csv中的每一行都需要创建一个新的html文件。csv行中的每个值都需要替换html中的values1 -7。我试着创建一个函数来处理这个问题,但是我不能让它改变html中的值。我可以手动更改该值,但我真的想知道如何使用函数进行更改。这不仅可以缩短编码量,还可以使其更加整洁和高效。
import string
import csv
#functions
#open the southpark csv file
def opensouthparkFile(openFile1):
southparklist = []
for i in openFile1:
i.strip()
l = i.split(",")
southparklist.append(l)
return southparklist
useinput = raw_input("Enter the name of the file that you would like to open:")
openFile1 = (open(useinput, "rU"))
openFile2 = open("Marsh", "w")
openFile3 = open("Broflovski", "w")
openFile4 = open("Cartman", "w")
openFile5 = open("McCormick", "w")
openFile6 = open("Scotch", "w")
southfile = opensouthparkFile(openFile1)
html = """
<html>
<P CLASS="western", ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=7 STYLE="font-size: 60pt">VALUE1</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=7 STYLE="fontSsize: 36pt">VALUE2</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=7 STYLE="font-size: 36pt"> VALUE3</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE4</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE5</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE6</FONT></P>
<P CLASS="western" ALIGN=CENTER STYLE="margin-top: 0.08in; margin-bottom: 0.25in">
<FONT SIZE=6 STYLE="font-size: 28pt"> VALUE7</FONT></P>
</html>
"""
#Function for replacing html files with southpark values
def replacehtml(html, somelist):
html = html.replace("VALUE1", somelist[0])
html = html.replace("VALUE2", somelist[1])
html = html.replace("VALUE3", somelist[2])
print somelist[1]
replacehtml(html, southfile[0])
replacehtml(html, southfile[1])
openFile2.write(html)
openFile2.close()发布于 2011-10-24 10:21:20
Python通过一种他们称为“按对象调用”的方案传递参数。当您在replacehtml函数中重新分配字符串时,这不会更改原始的html字符串,因为字符串是不可变的类型。
最快的修复方法可能是将字符串更改为函数的返回值。
def replacehtml(html, somelist):
html = html.replace("VALUE1", somelist[0])
html = html.replace("VALUE2", somelist[1])
html = html.replace("VALUE3", somelist[2])
print somelist[1]
return html
html = replacehtml(html, southfile[0])https://stackoverflow.com/questions/7870694
复制相似问题