我有一个包含一组数据的文本文件.写入新文件时,我正在使用for循环,但我的for循环为每行写入每一行.例如:我的数据是
Hello
World
This
Is
The
Text
Run Code Online (Sandbox Code Playgroud)
我的预期输出是使用xml标签来使用字符串标记数据.输出应该看起来像
<first>Hello</first>
<second>World</second>
<third>This</third>
""
""
<sixth>Text</sixth>
Run Code Online (Sandbox Code Playgroud)
等等.然而,循环我正在使用我的输出看起来像
<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>
""
""
Run Code Online (Sandbox Code Playgroud)
等等直到它结束.我该如何解决.我的代码是
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 == …Run Code Online (Sandbox Code Playgroud)