我是 python 新手,在使用小脚本时遇到了麻烦。
当前定义的 for 循环只运行一次。
这是代码(每行有 8 个元素):
#!/usr/local/bin/python
def string_to_xml(string):
entries = string.split(',')
result = "<item>\n"
result += "\t<distributor>" + entries[0] + "</distributor>\n"
result += "\t<number>" + entries[1] + "</number>\n"
result += "\t<description>" + entries[2] + "</description>\n"
result += "\t<brand>" + entries[3] + "</brand>\n"
result += "\t<casesize>" + entries[4] + "</casesize>\n"
result += "\t<unitsize>" + entries[5] + "</unitsize>\n"
result += "\t<caseprice>" + entries[6] + "</caseprice>\n"
result += "\t<unitprice>" + entries[7] + "</unitprice>\n"
result += "</item>"
return result
with open("input.csv") as csvfile:
for line in csvfile:
print string_to_xml(line)
像这样,它只打印一次调用 string_to_xml 的结果。如果我将 for 循环中的语句更改为:
for line in csvfile:
print line
它正确打印文件的每一行。
为什么调用我的函数 string_to_xml 会导致循环只运行一次?
编辑:如果有帮助,这是我的 csv 文件的前两行:
BIRITE,130405,Steak Sauce,Kraft,24,5oz,43.96,1.83
BIRITE,441045,Anchovy Filet,Maria,12,13oz,51.83,4.32