我有一个包含一组数据的文本文件.写入新文件时,我正在使用for循环,但我的for循环为每行写入每一行.例如:我的数据是
Hello World This Is The Text
我的预期输出是使用xml标签来使用字符串标记数据.输出应该看起来像
Hello World This "" ""Text
等等.然而,循环我正在使用我的输出看起来像
Hello Hello Hello Hello Hello Hello World World World World World World "" ""
等等直到它结束.我该如何解决.我的代码是
def tagData(filename): original = open(filename, 'r') new = open('test2.txt', 'w') index = 0 for line in original: if index%6 == 0: new.write(''+str(line).strip('\n')+' \n') index = index + 1 if index%6 == 1: new.write(''+str(line).strip('\n')+' \n') index = index + 1 if index%6 == 2: new.write(''+str(line).strip('\n')+' \n') index = index + 1 if index%6 == 3: new.write(''+str(line).strip('\n')+' \n') index = index + 1 if index%6 == 4: new.write(''+str(line).strip('\n')+' \n') index = index + 1 if index%6 == 5: new.write(''+str(line).strip('\n')+' \n') index = index + 1 original.close() new.close()
Jon Clements.. 7
我写的是:
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
逻辑的误解......