【问题标题】:add delimiter to fixed-width text file将定界符添加到固定宽度的文本文件
【发布时间】:2014-11-04 21:30:11
【问题描述】:

我正在尝试为固定宽度的文本文件添加分隔符。

这是我目前所拥有的:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('input.txt', 'r') as infile:
        for line in infile:
            newline = line[:4] + '|' + line[4:]
            outfile.write(newline)
outfile.close()

上面的代码在第 5 个字节处插入了一个管道。我现在想在列表中的下一个值处添加一个管道 (29)。我正在使用 Python 2.7。

【问题讨论】:

  • 你的代码中如何使用变量list
  • 我不认为这和你想的一样:line[:4]line[4:]
  • 你到底想在这里完成什么?

标签: python


【解决方案1】:

我认为这就是你想要做的:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('results.txt', 'r') as infile:
        for line in infile:
            iter = 0
            prev_position = 0
            position = list[iter]
            temp = []
            while position < len(line) and iter + 1 < len(list):
                iter += 1
                temp.append(line[prev_position:position])
                prev_position = position
                position = list[iter]
            temp.append(line[prev_position:])

            temp_str = ''.join(x + "|" for x in temp)
            temp_str = temp_str[:-1]

            outfile.write(temp_str)

这需要一个输入文件并在列表中的位置插入一个|。这将处理小于或大于列表中值的情况。

【讨论】:

    【解决方案2】:

    快速破解。检查它是否有效:

    list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
    with open('output.txt', 'w') as outfile:
        with open('input.txt', 'r') as infile:
            for line in infile:
                for l in list:
                    newline = line[:l] + '|' + line[l:]
                    outfile.write(newline)
    # outfile.close() -- not needed
    

    【讨论】:

    • 这是假设每一行的长度 > 169 个字符。每次迭代的大小也会发生变化。你需要考虑到这一点。
    • @KronoS 你是对的,我的错,但让我们看看 swhit 想要什么。也许迭代器会从列表中获取下一个值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多