我有一个包含一组数据的文本文件。写入新文件时,我使用的是 for 循环,但我的 for 循环会为每一行写入每一行。例如:我的数据是
Hello
World
This
Is
The
Text
我的预期输出是它使用 xml 标记来标记使用字符串的数据。输出应该类似于
<first>Hello</first>
<second>World</second>
<third>This</third>
""
""
<sixth>Text</sixth>
等等。但是在循环中我使用我的输出看起来像
<first>Hello</first>
<second>Hello</second>
<third>Hello</third>
<fourth>Hello</fourth>
<fifth>Hello</fifth>
<sixth>Hello</sixth>
<first>World</first>
<second>World</second>
<third>World</third>
<fourth>World</fourth>
<fifth>World</fifth>
<sixth>World</sixth>
""
""
以此类推,直到结束。我该如何解决。我的代码是
def tagData(filename):
original = open(filename, 'r')
new = open('test2.txt', 'w')
index = 0
for line in original:
if index%6 == 0:
new.write('<first>'+str(line).strip('\n')+'</first>\n')
index = index + 1
if index%6 == 1:
new.write('<second>'+str(line).strip('\n')+'</second>\n')
index = index + 1
if index%6 == 2:
new.write('<third>'+str(line).strip('\n')+'</third>\n')
index = index + 1
if index%6 == 3:
new.write('<fourth>'+str(line).strip('\n')+'</fourth>\n')
index = index + 1
if index%6 == 4:
new.write('<fifth>'+str(line).strip('\n')+'</fifth>\n')
index = index + 1
if index%6 == 5:
new.write('<sixth>'+str(line).strip('\n')+'</sixth>\n')
index = index + 1
original.close()
new.close()
请您参考如下方法:
我会这样写:
from itertools import cycle, izip
tags = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
with open('input') as fin, open('output', 'w') as fout:
for tag, line in izip(cycle(tags), fin):
fout.write('<{0}>{1}</{0}>\n'.format(tag, line.strip()))
这避免了混淆索引和 if 逻辑...
