【发布时间】:2017-05-15 19:21:39
【问题描述】:
我正在尝试在 csv 文件中写入我的代码结果,但不知何故它写入不正确。
我的代码是:
import xml.etree.ElementTree as ET
import csv
with open('myfile.xml', 'rt') as f:
tree = ET.parse(f)
for sentence in tree.iter('sentence'):
certainty = sentence.attrib.get('certainty')
ccue = sentence.find('ccue')
with open('new_file.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter='|',
quotechar='^', quoting=csv.QUOTE_MINIMAL)
if certainty and (ccue is not None):
writer.writerow(' %s | %s | %s' % (certainty, ''.join(sentence.itertext()), ccue.text))
else:
writer.writerow(' %s | | %s' % (certainty,sentence.text))
所以我想得到这样的结果: 确定性1|句子1|cue1 确定性2|句子2|cue2 ... 所以分隔符是|。
但我当前的代码将所有内容都写在 1 行中,并且这些分隔符无处不在:
| |c|e|r|t|a|i|n|
为什么会发生,我该如何解决?谢谢!
【问题讨论】:
-
请修正你的缩进
-
writerow接受一个可迭代的。阅读文档 -
另外一个问题:为什么要(重新)打开 CSV 文件并(重新)在循环中创建编写器?这些应该在循环外初始化。
-
@njzk2:严格来说,一个字符串是一个可迭代的。在这种情况下,它只会给出(咳咳)意想不到的结果。
-
@ZverArt:我怀疑你的缩进是错误的,所以
with被终止(并且文件关闭)在你进入循环之前。整个for循环需要在with的上下文中。