jbo*_*da5 1 python for-loop text-files
我有一个包含一组数据的文本文件.写入新文件时,我正在使用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 == 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()
Run Code Online (Sandbox Code Playgroud)
我写的是:
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()))
Run Code Online (Sandbox Code Playgroud)
这避免了对索引和if逻辑的误解......