用Python解析上传的CSV文件中的HTML
我正在使用GAE来托管一个需要从CSV文件获取输入的网站。在上传这个CSV文件后,我会把它转换成一个表格。不过,我遇到了一个关于Mac和Windows兼容性的问题。用Mac生成的CSV文件无法被识别,我收到了这个错误:
new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
这是我的 Python代码
def loop_html(thefile):
reader = csv.reader(thefile.file)
header = reader.next()
i=1
iter_html=""
for row in reader:
iter_html = iter_html +html_table(row,i) #generate inputs table
i=i+1
def html_table(row_inp,iter):
mai_temp=float(row_inp[0])
Input_header="""<table border="1">
<tr><H3>Batch Calculation of Iteration %s</H3></tr><br>
<tr>
<td><b>Input Name</b></td>
<td><b>Input value</b></td>
<td><b>Unit</b></td>
</tr>"""%(iter)
Input_mai="""<tr>
<td>Mass of Applied Ingredient Applied to Paddy</td>
<td>%s</td>
<td>kg</td>
</tr>""" %(mai_temp)
Inout_table = Input_header+Input_mai
return Inout_table
后来我把代码从'reader = csv.reader(thefile.file)'改成了'reader = csv.reader(open(thefile.file,'U'))',结果出现了不同类型的错误:
TypeError: coercing to Unicode: need string or buffer, cStringIO.StringO found
有没有人能看看我的代码,给我一些建议?谢谢!
1 个回答
1
我刚找到一个解决办法。使用'splitlines()'可以处理换行的问题。这里是相关的链接。
reader = csv.reader(thefile.file.read().splitlines())