如何使for-loop写特定行

 英萍维玟9856 发布于 2023-02-11 14:07

我有一个包含一组数据的文本文件.写入新文件时,我正在使用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}\n'.format(tag, line.strip()))

这避免了对索引和if逻辑的误解......

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有